Skip to main content

artifactize_core/
server.rs

1//! `artifactize server`: the shared remote review store over its own SQLite file.
2
3mod store;
4
5pub use store::{DATABASE, MAX_BYTES, MAX_ENTRIES, Revocation, Scope, Store, Token};
6
7use std::net::SocketAddr;
8
9use axum::{
10    Json, Router,
11    body::Bytes,
12    extract::{DefaultBodyLimit, Path, State},
13    http::{HeaderMap, HeaderValue, StatusCode, header},
14    response::{IntoResponse, Response},
15    routing::{get, post, put},
16};
17use serde::Deserialize;
18use serde_json::{Value, json};
19use tokio_util::sync::CancellationToken;
20
21use crate::{
22    remote::{MAX_FULL_BYTES, MAX_SUMMARY_BYTES, SCHEMA},
23    types::ReuseKey,
24};
25
26/// Loopback only by default: a review store is reachable from other machines only when its
27/// owner says so with `--listen`. 8417 is an unassigned port, fixed so that clients and docs
28/// agree on one default URL.
29pub const DEFAULT_LISTEN: &str = "127.0.0.1:8417";
30/// Bound one lookup's SQL work and response fan-out; clients batch larger key sets.
31pub(crate) const MAX_LOOKUP_KEYS: usize = 1000;
32/// Keep Axum's gross allocation cap slightly above a full record, so per-record
33/// validation can return the existing precise size error within that headroom.
34const BODY_LIMIT_HEADROOM: usize = 64 * 1024;
35
36/// The fields this store indexes or authorizes are typed at the HTTP edge. The
37/// remaining record is an opaque, extensible payload validated by its consumers.
38#[derive(serde::Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40struct PublishRecord {
41    schema: u32,
42    key: crate::types::ReuseKey,
43    verdict: crate::types::ExecutionStatus,
44    execution_id: crate::types::ExecutionId,
45    completed_at: String,
46    profile: PublishProfile,
47    #[serde(default, skip_serializing_if = "crate::config::Field::missing")]
48    execution: crate::config::Field<Value>,
49    #[serde(flatten)]
50    payload: serde_json::Map<String, Value>,
51}
52
53#[derive(serde::Serialize, Deserialize)]
54struct PublishProfile {
55    kind: crate::config::ProfileKind,
56    #[serde(flatten)]
57    options: serde_json::Map<String, Value>,
58}
59
60struct ApiError(StatusCode, String);
61
62impl ApiError {
63    fn new(status: StatusCode, message: impl Into<String>) -> Self {
64        Self(status, message.into())
65    }
66
67    fn internal(error: String) -> Self {
68        // Store errors never contain tokens; only their SHA-256 reaches SQLite.
69        // Logging is best effort: a failing stderr must not turn this error into a panic.
70        use std::io::Write as _;
71        let _ = writeln!(std::io::stderr().lock(), "Review store error: {error}");
72        Self::new(
73            StatusCode::INTERNAL_SERVER_ERROR,
74            "Internal review store error.",
75        )
76    }
77}
78
79impl IntoResponse for ApiError {
80    fn into_response(self) -> Response {
81        let mut response = (self.0, Json(json!({"error": self.1}))).into_response();
82        if self.0 == StatusCode::UNAUTHORIZED {
83            response
84                .headers_mut()
85                .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
86        }
87        response
88    }
89}
90
91struct Principal {
92    name: crate::types::TokenName,
93    scopes: Vec<Scope>,
94}
95
96async fn authenticate(
97    store: &Store,
98    headers: &HeaderMap,
99    required: Option<Scope>,
100) -> Result<Principal, ApiError> {
101    let token = headers
102        .get(header::AUTHORIZATION)
103        .and_then(|value| value.to_str().ok())
104        .and_then(|value| value.split_once(' '))
105        .filter(|(scheme, token)| scheme.eq_ignore_ascii_case("bearer") && !token.is_empty())
106        .map(|(_, token)| token.trim())
107        .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "A bearer token is required."))?;
108    let (name, scopes) = store
109        .authenticate(token)
110        .await
111        .map_err(ApiError::internal)?
112        .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "Invalid or revoked token."))?;
113    if let Some(scope) = required
114        && !scopes.contains(&scope)
115    {
116        return Err(ApiError::new(
117            StatusCode::FORBIDDEN,
118            format!("This token lacks the {} scope.", scope.name()),
119        ));
120    }
121    Ok(Principal { name, scopes })
122}
123
124/// What a client from before the 0.5 reuse key gets for its requests.
125const UPGRADE: &str = "This review store holds artifactize 0.5 reuse keys (store schema 3); upgrade this client to artifactize 0.5 or later.";
126
127async fn whoami(State(store): State<Store>, headers: HeaderMap) -> Result<Json<Value>, ApiError> {
128    let principal = authenticate(&store, &headers, None).await?;
129    Ok(Json(
130        json!({"principal": principal.name, "scopes": principal.scopes}),
131    ))
132}
133
134struct Lookup {
135    keys: Vec<crate::types::ReuseKey>,
136}
137
138/// Legacy object keys request an upgrade before current validation, even in mixed arrays
139/// or with unknown fields. Map parsing also retains the previous last-duplicate-key behavior.
140enum LookupRequest {
141    Current(Lookup),
142    Legacy,
143    Invalid,
144    TooMany,
145    MalformedKey,
146}
147impl LookupRequest {
148    /// Classify the complete envelope before validating identities: shape errors precede
149    /// count/key errors, and map-only legacy objects are handled by the visitor first.
150    fn current(keys: Vec<LookupKey>) -> Self {
151        if keys.iter().any(|key| !matches!(key, LookupKey::Current(_))) {
152            return Self::Invalid;
153        }
154        if keys.len() > MAX_LOOKUP_KEYS {
155            return Self::TooMany;
156        }
157        let keys = keys
158            .into_iter()
159            .map(|key| match key {
160                LookupKey::Current(key) => key.parse::<crate::types::ReuseKey>(),
161                _ => unreachable!("current lookup strings checked above"),
162            })
163            .collect::<Result<Vec<_>, _>>();
164        match keys {
165            Ok(keys) => Self::Current(Lookup { keys }),
166            Err(_) => Self::MalformedKey,
167        }
168    }
169}
170#[derive(Deserialize)]
171#[serde(untagged)]
172enum LookupKey {
173    Current(String),
174    Legacy(crate::json::Object<std::collections::BTreeMap<String, crate::json::Ignored>>),
175    Invalid(crate::json::Ignored),
176}
177impl<'de> Deserialize<'de> for LookupRequest {
178    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
179        struct RequestVisitor;
180        impl<'de> serde::de::Visitor<'de> for RequestVisitor {
181            type Value = LookupRequest;
182            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183                formatter.write_str("a lookup object")
184            }
185            fn visit_seq<S: serde::de::SeqAccess<'de>>(
186                self,
187                mut sequence: S,
188            ) -> Result<Self::Value, S::Error> {
189                // The former Lookup derive accepted one positional keys field. Objects here
190                // were ordinary invalid strings, never the map-only legacy upgrade path.
191                let keys = sequence.next_element::<crate::json::Optional<Vec<LookupKey>>>()?;
192                let mut extra = false;
193                while sequence.next_element::<crate::json::Ignored>()?.is_some() {
194                    extra = true;
195                }
196                match keys.and_then(|keys| keys.0) {
197                    Some(keys) if !extra => Ok(LookupRequest::current(keys)),
198                    _ => Ok(LookupRequest::Invalid),
199                }
200            }
201            fn visit_map<M: serde::de::MapAccess<'de>>(
202                self,
203                mut map: M,
204            ) -> Result<Self::Value, M::Error> {
205                let mut keys = crate::json::Optional::<Vec<LookupKey>>::default();
206                let mut unknown = false;
207                while let Some(field) = map.next_key::<String>()? {
208                    if field == "keys" {
209                        keys = map.next_value()?;
210                    } else {
211                        unknown = true;
212                        map.next_value::<crate::json::Ignored>()?;
213                    }
214                }
215                let Some(keys) = keys.0 else {
216                    return Ok(LookupRequest::Invalid);
217                };
218                if keys
219                    .iter()
220                    .any(|key| matches!(key, LookupKey::Legacy(crate::json::Object(_))))
221                {
222                    return Ok(LookupRequest::Legacy);
223                }
224                if unknown {
225                    return Ok(LookupRequest::Invalid);
226                }
227                Ok(LookupRequest::current(keys))
228            }
229        }
230        deserializer.deserialize_any(RequestVisitor)
231    }
232}
233
234fn parse_lookup(body: &[u8]) -> Result<Lookup, ApiError> {
235    let expected = || ApiError::new(StatusCode::BAD_REQUEST, "Expected {\"keys\":[KEY,...]}.");
236    match serde_json::from_slice::<LookupRequest>(body).map_err(|_| expected())? {
237        LookupRequest::Current(lookup) => Ok(lookup),
238        LookupRequest::Legacy => Err(ApiError::new(StatusCode::GONE, UPGRADE)),
239        LookupRequest::Invalid => Err(expected()),
240        LookupRequest::TooMany => Err(ApiError::new(
241            StatusCode::BAD_REQUEST,
242            format!("At most {MAX_LOOKUP_KEYS} keys per lookup."),
243        )),
244        LookupRequest::MalformedKey => Err(ApiError::new(
245            StatusCode::BAD_REQUEST,
246            "Keys are lowercase SHA-256 reuse keys.",
247        )),
248    }
249}
250
251#[cfg(test)]
252#[path = "server/tests/lookup_identity.rs"]
253mod lookup_identity_tests;
254#[cfg(test)]
255#[path = "server/tests/lookup.rs"]
256mod lookup_tests;
257
258async fn lookup(
259    State(store): State<Store>,
260    headers: HeaderMap,
261    body: Bytes,
262) -> Result<Response, ApiError> {
263    authenticate(&store, &headers, Some(Scope::Read)).await?;
264    let lookup = parse_lookup(&body)?;
265    let entries = store
266        .lookup(lookup.keys)
267        .await
268        .map_err(ApiError::internal)?;
269    // Stored records are already JSON; splice them without reparsing.
270    Ok((
271        [(header::CONTENT_TYPE, "application/json")],
272        format!("{{\"entries\":[{}]}}", entries.join(",")),
273    )
274        .into_response())
275}
276
277async fn publish(
278    State(store): State<Store>,
279    Path(key): Path<String>,
280    headers: HeaderMap,
281    body: Bytes,
282) -> Result<(StatusCode, Json<Value>), ApiError> {
283    let principal = authenticate(&store, &headers, Some(Scope::Publish)).await?;
284    let key = key.parse::<ReuseKey>().map_err(|_| {
285        ApiError::new(
286            StatusCode::BAD_REQUEST,
287            "Keys are lowercase SHA-256 reuse keys.",
288        )
289    })?;
290    let mut record: PublishRecord = serde_json::from_slice(&body)
291        .map_err(|_| ApiError::new(StatusCode::BAD_REQUEST, "Expected a JSON record."))?;
292    let limit = if !matches!(record.execution, crate::config::Field::Missing) {
293        MAX_FULL_BYTES
294    } else {
295        MAX_SUMMARY_BYTES
296    };
297    let completed_at = record.completed_at.parse::<crate::types::Timestamp>().ok();
298    let (true, Some(completed_at)) = (
299        record.schema == SCHEMA
300            && record.key == key
301            && matches!(
302                record.verdict,
303                crate::types::ExecutionStatus::Green | crate::types::ExecutionStatus::Red
304            )
305            && record.execution_id.valid_wire(),
306        completed_at,
307    ) else {
308        return Err(ApiError::new(
309            StatusCode::BAD_REQUEST,
310            format!(
311                "Records need schema {SCHEMA}, the path's key, a GREEN/RED verdict, a profile kind, an execution ID and an RFC 3339 completion time."
312            ),
313        ));
314    };
315    if body.len() > limit {
316        return Err(ApiError::new(
317            StatusCode::PAYLOAD_TOO_LARGE,
318            format!("Record exceeds {limit} bytes."),
319        ));
320    }
321    if record.profile.kind == crate::config::ProfileKind::Human
322        && !principal.scopes.contains(&Scope::Human)
323    {
324        return Err(ApiError::new(
325            StatusCode::FORBIDDEN,
326            "Human sign-offs require the human scope.",
327        ));
328    }
329    // The server, not the client, says who published and when.
330    record
331        .payload
332        .insert("publisher".into(), json!(principal.name));
333    record
334        .payload
335        .insert("publishedAt".into(), json!(crate::broker::now()));
336    let created = store
337        .insert(
338            &record.key,
339            &record.execution_id,
340            &principal.name,
341            completed_at,
342            serde_json::to_string(&record)
343                .map_err(|error| ApiError::internal(error.to_string()))?,
344        )
345        .await
346        .map_err(ApiError::internal)?;
347    Ok((
348        if created {
349            StatusCode::CREATED
350        } else {
351            StatusCode::OK
352        },
353        Json(json!({"created": created})),
354    ))
355}
356
357/// The 0.4 publish route, keyed by Eval definition hash and fingerprint.
358async fn legacy_publish() -> ApiError {
359    ApiError::new(StatusCode::GONE, UPGRADE)
360}
361
362pub fn router(store: Store) -> Router {
363    Router::new()
364        .route("/v1/whoami", get(whoami))
365        .route("/v1/lookup", post(lookup))
366        .route("/v1/entries/{key}", put(publish))
367        .route(
368            "/v1/entries/{eval_def_hash}/{fingerprint}",
369            put(legacy_publish),
370        )
371        .layer(DefaultBodyLimit::max(MAX_FULL_BYTES + BODY_LIMIT_HEADROOM))
372        .with_state(store)
373}
374
375/// Serve until cancelled; `ready` receives the bound address once listening.
376pub async fn serve(
377    store: Store,
378    listen: SocketAddr,
379    ready: impl FnOnce(SocketAddr) -> Result<(), String>,
380    cancellation: CancellationToken,
381) -> Result<(), String> {
382    let listener = crate::platform::net::http_listener(listen)
383        .map_err(|e| format!("Cannot listen on {listen}: {e}"))?;
384    ready(listener.local_addr().map_err(|e| e.to_string())?)?;
385    axum::serve(listener, router(store))
386        .with_graceful_shutdown(cancellation.cancelled_owned())
387        .await
388        .map_err(|e| e.to_string())
389}