1
//! The rotation script against a real session store: it is all that stands
2
//! between a refresh and a logged-out user, so it is proved rather than argued.
3

            
4
use super::{Redemption, Rotation, end_session, rotate_refresh};
5
use redis::AsyncCommands;
6

            
7
/// redis 1.x gives up on a reply after 500 ms, which a test process at low
8
/// priority on a loaded host can miss; the script, not the latency, is proved.
9
18
fn patient() -> redis::AsyncConnectionConfig {
10
18
    let wait = Some(std::time::Duration::from_secs(30));
11
18
    redis::AsyncConnectionConfig::new()
12
18
        .set_connection_timeout(wait)
13
18
        .set_response_timeout(wait)
14
18
}
15

            
16
18
async fn store() -> redis::aio::MultiplexedConnection {
17
18
    let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
18
18
    redis::Client::open(url)
19
18
        .expect("a valid session-store URL")
20
18
        .get_multiplexed_async_connection_with_config(&patient())
21
18
        .await
22
18
        .expect("the session store must be running for these tests")
23
18
}
24

            
25
30
async fn get(redis: &mut redis::aio::MultiplexedConnection, key: uuid::Uuid) -> Option<String> {
26
30
    redis.get(key.to_string()).await.expect("get")
27
30
}
28

            
29
/// A live session owned by `owner`, and the rotation that would replace it.
30
18
async fn seeded(redis: &mut redis::aio::MultiplexedConnection, owner: uuid::Uuid) -> Rotation {
31
18
    let rotation = Rotation {
32
18
        token_uuid: uuid::Uuid::new_v4(),
33
18
        owner,
34
18
        successor: uuid::Uuid::new_v4(),
35
18
        access_uuid: uuid::Uuid::new_v4(),
36
18
        superseded: None,
37
18
        refresh_ttl: 60,
38
18
        access_ttl: 60,
39
18
        grace: 30,
40
18
    };
41
18
    let _: () = redis
42
18
        .set_ex(rotation.token_uuid.to_string(), owner.to_string(), 60)
43
18
        .await
44
18
        .expect("seed");
45
18
    rotation
46
18
}
47

            
48
22
async fn redeem(redis: &mut redis::aio::MultiplexedConnection, rotation: &Rotation) -> Redemption {
49
22
    rotate_refresh(redis, rotation).await.expect("rotate")
50
22
}
51

            
52
6
async fn ttl(redis: &mut redis::aio::MultiplexedConnection, key: uuid::Uuid) -> i64 {
53
6
    redis.ttl(key.to_string()).await.expect("ttl")
54
6
}
55

            
56
#[tokio::test]
57
2
async fn a_rotation_replaces_the_session_and_the_second_call_reuses_it() {
58
2
    let mut redis = store().await;
59
2
    let owner = uuid::Uuid::new_v4();
60
2
    let rotation = seeded(&mut redis, owner).await;
61

            
62
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
63
2
    assert_eq!(
64
2
        get(&mut redis, rotation.successor).await,
65
2
        Some(owner.to_string())
66
    );
67
2
    assert_eq!(
68
2
        get(&mut redis, rotation.access_uuid).await,
69
2
        Some(owner.to_string())
70
    );
71
2
    assert_eq!(
72
2
        get(&mut redis, rotation.token_uuid).await,
73
2
        Some(format!(
74
2
            "rotated:{owner}:{}:{}",
75
2
            rotation.successor, rotation.access_uuid
76
2
        ))
77
    );
78
2
    assert!(ttl(&mut redis, rotation.token_uuid).await <= 30);
79

            
80
2
    let later = Rotation {
81
2
        successor: uuid::Uuid::new_v4(),
82
2
        ..rotation
83
2
    };
84
2
    assert_eq!(redeem(&mut redis, &later).await, Redemption::Reused);
85
2
    assert_eq!(get(&mut redis, later.successor).await, None);
86
2
    assert!(
87
2
        ttl(&mut redis, later.token_uuid).await <= 30,
88
2
        "a reuse must not extend the marker"
89
2
    );
90
2
}
91

            
92
#[tokio::test]
93
2
async fn a_rotated_session_is_refused_once_the_grace_has_passed() {
94
2
    let mut redis = store().await;
95
    let rotation = Rotation {
96
2
        grace: 1,
97
2
        ..seeded(&mut redis, uuid::Uuid::new_v4()).await
98
    };
99

            
100
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
101
2
    tokio::time::sleep(std::time::Duration::from_millis(2100)).await;
102
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Refused);
103
2
}
104

            
105
#[tokio::test]
106
2
async fn another_owners_rotated_session_is_refused() {
107
2
    let mut redis = store().await;
108
2
    let rotation = seeded(&mut redis, uuid::Uuid::new_v4()).await;
109
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
110

            
111
2
    let impostor = Rotation {
112
2
        owner: uuid::Uuid::new_v4(),
113
2
        ..rotation
114
2
    };
115
2
    assert_eq!(redeem(&mut redis, &impostor).await, Redemption::Refused);
116
2
}
117

            
118
#[tokio::test]
119
2
async fn a_key_with_a_sub_second_ttl_keeps_its_remaining_life() {
120
2
    let mut redis = store().await;
121
2
    let owner = uuid::Uuid::new_v4();
122
2
    let previous = uuid::Uuid::new_v4();
123
2
    let _: () = redis
124
2
        .pset_ex(previous.to_string(), owner.to_string(), 300)
125
2
        .await
126
2
        .expect("seed previous access");
127
    let rotation = Rotation {
128
2
        superseded: Some(previous),
129
2
        ..seeded(&mut redis, owner).await
130
    };
131

            
132
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
133
2
    let remaining: i64 = redis.pttl(previous.to_string()).await.expect("pttl");
134
2
    assert!((1..=300).contains(&remaining), "pttl was {remaining}");
135
2
}
136

            
137
#[tokio::test]
138
2
async fn logout_deletes_the_successors_a_marker_names() {
139
2
    let mut redis = store().await;
140
2
    let owner = uuid::Uuid::new_v4();
141
2
    let rotation = seeded(&mut redis, owner).await;
142
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
143
2
    let access = uuid::Uuid::new_v4();
144

            
145
2
    end_session(&mut redis, rotation.token_uuid, access, owner)
146
2
        .await
147
2
        .expect("end");
148

            
149
2
    for key in [
150
2
        rotation.token_uuid,
151
2
        rotation.successor,
152
2
        rotation.access_uuid,
153
2
    ] {
154
6
        assert_eq!(get(&mut redis, key).await, None);
155
2
    }
156
2
}
157

            
158
#[tokio::test]
159
2
async fn logout_never_follows_another_owners_marker() {
160
2
    let mut redis = store().await;
161
2
    let owner = uuid::Uuid::new_v4();
162
2
    let rotation = seeded(&mut redis, owner).await;
163
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
164

            
165
2
    end_session(
166
2
        &mut redis,
167
2
        rotation.token_uuid,
168
2
        uuid::Uuid::new_v4(),
169
2
        uuid::Uuid::new_v4(),
170
2
    )
171
2
    .await
172
2
    .expect("end");
173

            
174
2
    assert_eq!(get(&mut redis, rotation.token_uuid).await, None);
175
2
    for key in [rotation.successor, rotation.access_uuid] {
176
4
        assert_eq!(get(&mut redis, key).await, Some(owner.to_string()));
177
2
    }
178
2
}
179

            
180
/// Refreshing while still holding an access token supersedes it. Logout
181
/// only ever sees the newest pair, so a superseded token left alive would
182
/// outlive the session; it keeps only the grace for requests already in flight.
183
#[tokio::test]
184
2
async fn a_rotation_shortens_the_access_token_it_supersedes_to_the_grace() {
185
2
    let mut redis = store().await;
186
2
    let owner = uuid::Uuid::new_v4();
187
2
    let previous = uuid::Uuid::new_v4();
188
2
    let _: () = redis
189
2
        .set_ex(previous.to_string(), owner.to_string(), 60)
190
2
        .await
191
2
        .expect("seed previous access");
192
    let rotation = Rotation {
193
2
        superseded: Some(previous),
194
2
        ..seeded(&mut redis, owner).await
195
    };
196

            
197
2
    assert_eq!(redeem(&mut redis, &rotation).await, Redemption::Rotated);
198
2
    assert_eq!(get(&mut redis, previous).await, Some(owner.to_string()));
199
2
    let remaining = ttl(&mut redis, previous).await;
200
2
    assert!((1..=30).contains(&remaining), "ttl was {remaining}");
201
2
    assert_eq!(
202
2
        get(&mut redis, rotation.access_uuid).await,
203
2
        Some(owner.to_string())
204
2
    );
205
2
}
206

            
207
#[tokio::test]
208
2
async fn a_foreign_owner_consumes_nothing() {
209
2
    let mut redis = store().await;
210
2
    let owner = uuid::Uuid::new_v4();
211
2
    let rotation = seeded(&mut redis, owner).await;
212
2
    let (session, successor) = (rotation.token_uuid, rotation.successor);
213

            
214
2
    let impostor = Rotation {
215
2
        owner: uuid::Uuid::new_v4(),
216
2
        ..rotation
217
2
    };
218
2
    assert_eq!(redeem(&mut redis, &impostor).await, Redemption::Refused);
219
2
    assert_eq!(get(&mut redis, session).await, Some(owner.to_string()));
220
2
    assert_eq!(get(&mut redis, successor).await, None);
221
2
}
222

            
223
/// A failing `redis.call` aborts the script with earlier writes applied, so
224
/// the rotated marker must come last or a bad TTL consumes the session.
225
#[tokio::test]
226
2
async fn a_rotation_that_cannot_write_leaves_the_session_intact() {
227
2
    let mut redis = store().await;
228
2
    let owner = uuid::Uuid::new_v4();
229
2
    let rotation = seeded(&mut redis, owner).await;
230
2
    let session = rotation.token_uuid;
231

            
232
2
    let broken = Rotation {
233
2
        refresh_ttl: 0,
234
2
        ..rotation
235
2
    };
236
2
    assert!(rotate_refresh(&mut redis, &broken).await.is_err());
237
2
    assert_eq!(get(&mut redis, session).await, Some(owner.to_string()));
238
2
}