-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_session.rs
More file actions
218 lines (197 loc) · 7.75 KB
/
database_session.rs
File metadata and controls
218 lines (197 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
//! Persisted database-scoped JWT session.
//!
//! Minted by `POST /v1/auth/database` (grant_type=existing_database +
//! database_id), refreshed via the same endpoint with
//! grant_type=refresh_token. Bound to a single database + workspace;
//! the JWT carries workspace + database read/write scope. The server
//! does not rotate the refresh token.
//!
//! Stored at `~/.hotdata/database_session.json` (mode 0600).
use crate::config;
use crate::util;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
// The refresh path below (REFRESH_LEEWAY_SECONDS, now_unix, MintResponse,
// redact, refresh, session_from_response) mirrors sandbox_session.rs and is
// covered by tests, but has no production caller yet: it's reserved for when
// a child of `databases run` re-mints an expiring HOTDATA_DATABASE_TOKEN
// (the child-side ApiClient consumption is not wired up yet). Annotated
// #[allow(dead_code)] until that lands so the build stays warning-clean.
#[allow(dead_code)]
const REFRESH_LEEWAY_SECONDS: u64 = 60;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DatabaseSession {
pub access_token: String,
pub refresh_token: String,
pub database_id: String,
pub workspace_id: String,
pub access_expires_at: u64,
pub refresh_expires_at: u64,
}
pub fn session_path() -> Option<PathBuf> {
config::config_dir().ok().map(|d| d.join("database_session.json"))
}
#[allow(dead_code)] // Reserved for flows that re-use a cached database session.
pub fn load() -> Option<DatabaseSession> {
let path = session_path()?;
let raw = fs::read_to_string(&path).ok()?;
serde_json::from_str(&raw).ok()
}
pub fn save(session: &DatabaseSession) -> Result<(), String> {
let path = session_path().ok_or_else(|| "no database session path available".to_string())?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir failed: {e}"))?;
}
let json = serde_json::to_string_pretty(session)
.map_err(|e| format!("serialize failed: {e}"))?;
use std::os::unix::fs::OpenOptionsExt;
let mut f = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.mode(0o600)
.open(&path)
.map_err(|e| format!("open failed: {e}"))?;
f.write_all(json.as_bytes())
.map_err(|e| format!("write failed: {e}"))?;
Ok(())
}
#[allow(dead_code)] // Reserved for flows that re-use a cached database session.
pub fn clear() {
if let Some(path) = session_path() {
let _ = fs::remove_file(path);
}
}
#[allow(dead_code)] // Part of the reserved refresh path (see REFRESH_LEEWAY_SECONDS).
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[allow(dead_code)] // Part of the reserved refresh path (see REFRESH_LEEWAY_SECONDS).
#[derive(Deserialize)]
pub(crate) struct MintResponse {
token: String,
refresh_token: String,
database_id: String,
expires_in: u64,
refresh_expires_in: u64,
}
#[allow(dead_code)] // Part of the reserved refresh path (see REFRESH_LEEWAY_SECONDS).
fn redact(s: &str) -> String {
util::mask_credential(s)
}
/// Trade a refresh token for a fresh database JWT (no rotation). Same
/// endpoint as the new-mint path: `POST /v1/auth/database` with
/// grant_type=refresh_token.
#[allow(dead_code)] // Part of the reserved refresh path (see REFRESH_LEEWAY_SECONDS).
pub fn refresh(api_url: &str, refresh_token: &str) -> Result<DatabaseSession, String> {
let url = format!("{}/auth/database", api_url.trim_end_matches('/'));
let body = serde_json::json!({
"grant_type": "refresh_token",
"refresh_token": refresh_token,
});
let body_log = serde_json::json!({
"grant_type": "refresh_token",
"refresh_token": redact(refresh_token),
});
let client = reqwest::blocking::Client::new();
let req = client.post(&url).json(&body);
let (status, body_text) = util::send_debug_with_redaction(
&client,
req,
Some(&body_log),
&["token", "refresh_token"],
)
.map_err(|e| format!("connection error: {e}"))?;
if !status.is_success() {
return Err(format!("database refresh failed: HTTP {status}: {body_text}"));
}
let resp: MintResponse = serde_json::from_str(&body_text)
.map_err(|e| format!("malformed refresh response: {e}"))?;
Ok(session_from_response(resp, String::new()))
}
/// Build a [`DatabaseSession`] from a mint/refresh response. The mint
/// response doesn't carry the workspace public_id, so the caller passes
/// it in (it's what the JWT's `workspaces` claim restricts the bearer
/// to). For refresh, `workspace_id` is left blank — the caller fills it
/// from the prior session, since the database-id ↔ workspace mapping is
/// invariant across refreshes.
#[allow(dead_code)] // Part of the reserved refresh path (see REFRESH_LEEWAY_SECONDS).
pub(crate) fn session_from_response(resp: MintResponse, workspace_id: String) -> DatabaseSession {
let now = now_unix();
DatabaseSession {
access_token: resp.token,
refresh_token: resp.refresh_token,
database_id: resp.database_id,
workspace_id,
access_expires_at: now + resp.expires_in,
refresh_expires_at: now + resp.refresh_expires_in,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::test_helpers::with_temp_config_dir;
fn mk_session(access_offset: i64, refresh_offset: i64) -> DatabaseSession {
let now = now_unix() as i64;
DatabaseSession {
access_token: "cached".into(),
refresh_token: "cached-refresh".into(),
database_id: "dbid_abc".into(),
workspace_id: "work_xyz".into(),
access_expires_at: (now + access_offset).max(0) as u64,
refresh_expires_at: (now + refresh_offset).max(0) as u64,
}
}
#[test]
fn round_trip() {
let (_tmp, _guard) = with_temp_config_dir();
let s = mk_session(3600, 86400);
save(&s).unwrap();
let loaded = load().unwrap();
assert_eq!(loaded.access_token, "cached");
assert_eq!(loaded.database_id, "dbid_abc");
assert_eq!(loaded.workspace_id, "work_xyz");
}
#[test]
fn file_is_mode_0600() {
use std::os::unix::fs::PermissionsExt;
let (_tmp, _guard) = with_temp_config_dir();
save(&mk_session(60, 60)).unwrap();
let mode = fs::metadata(session_path().unwrap()).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
#[test]
fn refresh_posts_grant_type_to_database_endpoint() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/auth/database")
.match_body(mockito::Matcher::JsonString(
r#"{"grant_type":"refresh_token","refresh_token":"stable-refresh"}"#.to_string(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"ok":true,"token":"new-jwt","refresh_token":"stable-refresh","database_id":"dbid_abc","expires_in":300,"refresh_expires_in":259200}"#,
)
.create();
let s = refresh(&server.url(), "stable-refresh").unwrap();
m.assert();
assert_eq!(s.access_token, "new-jwt");
assert_eq!(s.refresh_token, "stable-refresh");
assert_eq!(s.database_id, "dbid_abc");
}
#[test]
fn refresh_http_error() {
let mut server = mockito::Server::new();
let m = server.mock("POST", "/auth/database").with_status(401).create();
let err = refresh(&server.url(), "x").unwrap_err();
m.assert();
assert!(err.contains("401"));
}
}