sim-lib-openai-server 0.3.0

OpenAI-shaped gateway routes and fixture media surfaces for SIM.
Documentation
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::sync::{Arc, Mutex, OnceLock};

use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};
use sim_citizen_derive::non_citizen;
use sim_kernel::{
    CapabilityName, CapabilitySet, Cx, DefaultFactory, Error, Expr, GrantSeat, NoopEvalPolicy,
    Object, ObjectCompat, Result, Symbol, Table, Value,
};
use sim_lib_net_core::hex_encode;

use crate::objects::GatewayRequest;

macro_rules! grant_into_result {
    ($grant:expr) => {{
        #[allow(clippy::let_unit_value)]
        let grant_result = $grant;
        #[allow(clippy::unit_arg)]
        grant_result.into_result()
    }};
}

/// Object tag identifying a serialized [`OpenAiGatewayKey`] descriptor.
pub const OPENAI_GATEWAY_KEY_OBJECT: &str = "openai-gateway/key";
const REDACTED_HEADER_VALUE: &str = "[redacted]";

/// An API key registered with the gateway, holding its hashed secret and the
/// capability ceiling it grants.
///
/// The plaintext secret is never stored; the key is identified by the SHA-256
/// hash of the secret and carries the [`CapabilitySet`] that bounds what a
/// request authenticated with it may do.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_citizen(
    reason = "gateway key object stores redacted credential policy; serializable projection is openai/GatewayKey descriptor",
    kind = "handle",
    descriptor = "openai/GatewayKey"
)]
pub struct OpenAiGatewayKey {
    id: String,
    key_hash: String,
    capabilities: CapabilitySet,
    default_policy: Expr,
}

impl OpenAiGatewayKey {
    /// Returns a key from a precomputed secret hash and its capability ceiling.
    pub fn new(key_hash: impl Into<String>, capabilities: CapabilitySet) -> Self {
        let key_hash = key_hash.into();
        let id = key_id(&key_hash);
        let default_policy = key_default_policy_expr(&capabilities);
        Self {
            id,
            key_hash,
            capabilities,
            default_policy,
        }
    }

    /// Returns a key built by hashing `secret`, with the given capability ceiling.
    pub fn from_secret(secret: &str, capabilities: CapabilitySet) -> Self {
        Self::new(key_hash(secret), capabilities)
    }

    /// Returns the public key id (a `key_`-prefixed hash fragment).
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the hex SHA-256 hash of the key secret.
    pub fn key_hash(&self) -> &str {
        &self.key_hash
    }

    /// Returns a short, non-verifier fingerprint for reports.
    pub fn fingerprint(&self) -> String {
        key_fingerprint(&self.key_hash)
    }

    /// Returns the capability ceiling granted by this key.
    pub fn capabilities(&self) -> &CapabilitySet {
        &self.capabilities
    }

    /// Returns the default policy expression derived from the capability ceiling.
    pub fn default_policy(&self) -> &Expr {
        &self.default_policy
    }

    /// Returns the key as a serializable map descriptor.
    pub fn to_expr(&self) -> Expr {
        Expr::Map(vec![
            field("object", Expr::String(OPENAI_GATEWAY_KEY_OBJECT.to_owned())),
            field("id", Expr::String(self.id.clone())),
            field("fingerprint", Expr::String(self.fingerprint())),
            field("capabilities", capabilities_expr(&self.capabilities)),
            field("default-policy", self.default_policy.clone()),
        ])
    }
}

impl Object for OpenAiGatewayKey {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok(format!("#<openai-gateway-key {}>", self.id))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ObjectCompat for OpenAiGatewayKey {
    fn as_expr(&self, _cx: &mut Cx) -> Result<Expr> {
        Ok(self.to_expr())
    }
}

/// Thread-safe table of gateway API keys indexed by secret hash.
///
/// Keys are stored in a SIM table behind a shared mutex so the same table can
/// be cloned across route state; an anonymous capability ceiling applies to
/// requests that present no recognized key.
#[derive(Clone)]
pub struct OpenAiKeyTable {
    inner: Arc<OpenAiKeyTableInner>,
}

struct OpenAiKeyTableInner {
    cx: Mutex<Cx>,
    keys: Value,
    anonymous: CapabilitySet,
}

impl OpenAiKeyTable {
    /// Returns an empty key table with no anonymous capabilities.
    pub fn new() -> Result<Self> {
        Self::with_anonymous(CapabilitySet::new())
    }

    /// Returns an empty key table whose unauthenticated requests get `anonymous`.
    pub fn with_anonymous(anonymous: CapabilitySet) -> Result<Self> {
        let cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
        let keys = cx.factory().table(Vec::new())?;
        Ok(Self {
            inner: Arc::new(OpenAiKeyTableInner {
                cx: Mutex::new(cx),
                keys,
                anonymous,
            }),
        })
    }

    /// Hashes `secret`, registers it with `capabilities`, and returns the new key.
    pub fn add_secret(
        &self,
        secret: &str,
        capabilities: CapabilitySet,
    ) -> Result<OpenAiGatewayKey> {
        let key = OpenAiGatewayKey::from_secret(secret, capabilities);
        self.add_key(key.clone())?;
        Ok(key)
    }

    /// Inserts an already-constructed key, indexing it by its secret hash.
    pub fn add_key(&self, key: OpenAiGatewayKey) -> Result<()> {
        let mut cx = self.cx()?;
        let value = cx.factory().opaque(Arc::new(key.clone()))?;
        table_impl(&self.inner.keys)?.set(&mut cx, Symbol::new(key.key_hash()), value)
    }

    /// Returns the registered key matching `secret`, or `None` if unknown.
    pub fn key_for_secret(&self, secret: &str) -> Result<Option<OpenAiGatewayKey>> {
        self.key_for_hash(&key_hash(secret))
    }

    /// Returns the key authenticating `request`, reading its bearer/api-key header.
    pub fn key_for_request(&self, request: &GatewayRequest) -> Result<Option<OpenAiGatewayKey>> {
        presented_key(request)
            .map(|secret| self.key_for_secret(secret))
            .unwrap_or(Ok(None))
    }

    /// Returns all registered keys.
    pub fn list_keys(&self) -> Result<Vec<OpenAiGatewayKey>> {
        let mut cx = self.cx()?;
        Ok(table_impl(&self.inner.keys)?
            .entries(&mut cx)?
            .into_iter()
            .filter_map(|(_, value)| value.object().downcast_ref::<OpenAiGatewayKey>().cloned())
            .collect())
    }

    /// Returns the capabilities `request` may exercise.
    ///
    /// The result is the key's ceiling (or the anonymous ceiling when no key is
    /// presented), intersected with any capabilities the request body explicitly
    /// requests, so a request can only narrow -- never widen -- its key's grant.
    pub fn effective_capabilities(&self, request: &GatewayRequest) -> Result<CapabilitySet> {
        let ceiling = self
            .key_for_request(request)?
            .map(|key| key.capabilities().clone())
            .unwrap_or_else(|| self.inner.anonymous.clone());
        Ok(requested_capabilities(request)
            .map(|requested| intersect_capabilities(&requested, &ceiling))
            .unwrap_or(ceiling))
    }

    /// Runs `f` with `cx` scoped to the request's effective capabilities.
    pub fn with_effective_capabilities<T>(
        &self,
        cx: &mut Cx,
        request: &GatewayRequest,
        f: impl FnOnce(&mut Cx) -> Result<T>,
    ) -> Result<T> {
        cx.with_capabilities(self.effective_capabilities(request)?, f)
    }

    fn key_for_hash(&self, hash: &str) -> Result<Option<OpenAiGatewayKey>> {
        let mut cx = self.cx()?;
        let value = table_impl(&self.inner.keys)?.get(&mut cx, Symbol::new(hash))?;
        Ok(value.object().downcast_ref::<OpenAiGatewayKey>().cloned())
    }

    fn cx(&self) -> Result<std::sync::MutexGuard<'_, Cx>> {
        self.inner
            .cx
            .lock()
            .map_err(|_| Error::PoisonedLock("openai gateway key table"))
    }
}

impl Default for OpenAiKeyTable {
    fn default() -> Self {
        Self::new().expect("in-memory SIM key table creation is infallible")
    }
}

/// Returns the process-wide shared gateway key table, initializing it on first use.
pub fn global_openai_key_table() -> &'static OpenAiKeyTable {
    static TABLE: OnceLock<OpenAiKeyTable> = OnceLock::new();
    TABLE.get_or_init(OpenAiKeyTable::default)
}

/// Returns the lowercase hex SHA-256 hash of a key secret.
pub fn key_hash(secret: &str) -> String {
    hex_encode(&Sha256::digest(secret.as_bytes()))
}

/// Returns a copy of `request` with sensitive auth headers replaced by `[redacted]`.
pub fn redacted_gateway_request(request: &GatewayRequest) -> GatewayRequest {
    GatewayRequest::new(
        request.method().to_owned(),
        request.path().to_owned(),
        redact_headers(request.headers()),
        request.body().to_vec(),
    )
}

/// Grants every capability in `capabilities` to `cx`, through the host-held
/// `seat` minted when `cx` was constructed.
pub fn grant_capability_set(
    seat: &GrantSeat,
    cx: &mut Cx,
    capabilities: &CapabilitySet,
) -> Result<()> {
    for capability in capabilities.iter().cloned() {
        grant_into_result!(seat.grant(cx, capability))?;
    }
    Ok(())
}

trait GrantOutcome {
    fn into_result(self) -> Result<()>;
}

impl GrantOutcome for () {
    fn into_result(self) -> Result<()> {
        Ok(())
    }
}

impl GrantOutcome for Result<()> {
    fn into_result(self) -> Result<()> {
        self
    }
}

fn key_id(hash: &str) -> String {
    let prefix_len = hash.len().min(12);
    format!("key_{}", &hash[..prefix_len])
}

fn key_fingerprint(hash: &str) -> String {
    let prefix_len = hash.len().min(8);
    format!("sha256:{}...", &hash[..prefix_len])
}

fn key_default_policy_expr(capabilities: &CapabilitySet) -> Expr {
    Expr::Map(vec![field(
        "capability-ceiling",
        capabilities_expr(capabilities),
    )])
}

fn capabilities_expr(capabilities: &CapabilitySet) -> Expr {
    Expr::Vector(
        capabilities
            .iter()
            .map(|capability| Expr::String(capability.as_str().to_owned()))
            .collect(),
    )
}

fn requested_capabilities(request: &GatewayRequest) -> Option<CapabilitySet> {
    let body = serde_json::from_slice::<JsonValue>(request.body()).ok()?;
    let object = body.as_object()?;
    object
        .get("capabilities")
        .or_else(|| {
            object
                .get("sim")
                .and_then(JsonValue::as_object)
                .and_then(|sim| sim.get("capabilities"))
        })
        .and_then(capability_set_from_json)
}

fn capability_set_from_json(value: &JsonValue) -> Option<CapabilitySet> {
    let mut capabilities = CapabilitySet::new();
    match value {
        JsonValue::String(name) => capabilities.insert(CapabilityName::new(name.clone())),
        JsonValue::Array(items) => {
            for item in items {
                let name = item.as_str()?;
                capabilities.insert(CapabilityName::new(name.to_owned()));
            }
        }
        _ => return None,
    }
    Some(capabilities)
}

fn intersect_capabilities(left: &CapabilitySet, right: &CapabilitySet) -> CapabilitySet {
    let mut capabilities = CapabilitySet::new();
    for capability in left.iter() {
        if right.contains(capability) {
            capabilities.insert(capability.clone());
        }
    }
    capabilities
}

fn presented_key(request: &GatewayRequest) -> Option<&str> {
    for (name, value) in request.headers() {
        if name.eq_ignore_ascii_case("authorization") {
            let value = value.trim();
            if let Some((scheme, token)) = value.split_once(' ')
                && scheme.eq_ignore_ascii_case("bearer")
            {
                let token = token.trim();
                if !token.is_empty() {
                    return Some(token);
                }
            }
        }
        if is_api_key_header(name) {
            let value = value.trim();
            if !value.is_empty() {
                return Some(value);
            }
        }
    }
    None
}

fn redact_headers(headers: &[(String, String)]) -> Vec<(String, String)> {
    headers
        .iter()
        .map(|(name, value)| {
            if is_sensitive_header(name) {
                (name.clone(), REDACTED_HEADER_VALUE.to_owned())
            } else {
                (name.clone(), value.clone())
            }
        })
        .collect()
}

fn is_api_key_header(name: &str) -> bool {
    name.eq_ignore_ascii_case("x-api-key")
        || name.eq_ignore_ascii_case("api-key")
        || name.eq_ignore_ascii_case("openai-api-key")
        || name.eq_ignore_ascii_case("x-openai-api-key")
}

fn is_sensitive_header(name: &str) -> bool {
    name.eq_ignore_ascii_case("authorization")
        || name.eq_ignore_ascii_case("proxy-authorization")
        || is_api_key_header(name)
}

fn table_impl(value: &Value) -> Result<&dyn Table> {
    value.object().as_table_impl().ok_or(Error::TypeMismatch {
        expected: "SIM table",
        found: "non-table",
    })
}

use sim_value::build::entry as field;