Skip to content
pi-c Documentation
Login

Documentation

/* MCP OAuth unit tests: WWW-Authenticate parsing, URL/key normalization, HTTPS guard, RFC 8707
 * resource check, RFC 9207 iss check, step-up scope union, config JSON round-trip, and sealed
 * picu_mcp_oauth storage across pic auth rekey and reset. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "cred.h"
#include "mcp_oauth.h"
#include "pic.h"
#include "platform.h"
#include "sqlite3.h"
#include "userdb.h"

static int failures;

static void expect(int ok, const char *what) {
    if (!ok) {
        fprintf(stderr, "FAIL: %s\n", what);
        failures++;
    }
}

static void test_www_auth(void) {
    pic_mcp_oauth_challenge ch;

    pic_mcp_oauth_parse_www_auth(NULL, &ch);
    expect(!ch.is_oauth && !ch.resource_metadata[0] && !ch.scope[0], "NULL header gives empty challenge");

    pic_mcp_oauth_parse_www_auth("Basic realm=\"example\"", &ch);
    expect(!ch.is_oauth, "Basic scheme ignored");

    pic_mcp_oauth_parse_www_auth(
        "Bearer realm=\"mcp\", resource_metadata=\"https://mcp.example.com/.well-known/oauth-protected-resource\", "
        "scope=\"mcp:read mcp:write\", error=\"insufficient_scope\", error_description=\"need \\\"write\\\" \\\\ more\"",
        &ch);
    expect(ch.is_oauth == 1, "Bearer recognized");
    expect(strcmp(ch.resource_metadata, "https://mcp.example.com/.well-known/oauth-protected-resource") == 0,
           "resource_metadata parsed");
    expect(strcmp(ch.scope, "mcp:read mcp:write") == 0, "quoted scope parsed");
    expect(strcmp(ch.error, "insufficient_scope") == 0, "error parsed");
    expect(strcmp(ch.error_description, "need \"write\" \\ more") == 0, "escaped quotes and backslash unescaped");

    /* DPoP with unquoted params and empty scope */
    pic_mcp_oauth_parse_www_auth("DPoP error=invalid_token, scope=\"\", RESOURCE_METADATA=https://a.example/rm", &ch);
    expect(ch.is_oauth == 1, "DPoP recognized");
    expect(strcmp(ch.error, "invalid_token") == 0, "unquoted error parsed");
    expect(ch.scope[0] == '\0', "empty quoted scope treated as absent");
    expect(strcmp(ch.resource_metadata, "https://a.example/rm") == 0, "case-insensitive unquoted resource_metadata");

    /* Multiple challenges in one header: Basic followed by Bearer */
    pic_mcp_oauth_parse_www_auth("Basic realm=\"x\", Bearer error=\"insufficient_scope\", scope=\"admin\"", &ch);
    expect(ch.is_oauth == 1 && strcmp(ch.error, "insufficient_scope") == 0 && strcmp(ch.scope, "admin") == 0,
           "second Bearer challenge after Basic parsed");
}

static void test_server_key_and_urls(void) {
    char k1[256], k2[256], err[256];

    expect(pic_mcp_oauth_server_key("My-Server", "HTTPS://Example.COM:443/mcp/", k1, sizeof k1) > 0, "key1 built");
    expect(pic_mcp_oauth_server_key("my_server", "https://example.com/mcp#frag", k2, sizeof k2) > 0, "key2 built");
    expect(strcmp(k1, "my_server|https://example.com/mcp") == 0, "key1 normalized");
    expect(strcmp(k1, k2) == 0, "equivalent name/URL produce identical server_key");

    expect(pic_mcp_oauth_server_key("local", "HTTP://LOCALHOST:80/", k1, sizeof k1) > 0, "root http key");
    expect(strcmp(k1, "local|http://localhost") == 0, "default port 80 and trailing slash stripped");

    expect(pic_mcp_oauth_server_key("p", "http://127.0.0.1:8080/api/?x=1", k1, sizeof k1) > 0, "custom port + query");
    expect(strcmp(k1, "p|http://127.0.0.1:8080/api?x=1") == 0, "non-default port and query preserved");

    expect(pic_mcp_oauth_server_key("v6", "http://[::1]:9000/mcp/", k1, sizeof k1) > 0, "ipv6 loopback key");
    expect(strcmp(k1, "v6|http://[::1]:9000/mcp") == 0, "ipv6 host preserved");

    /* HTTPS guard */
    expect(pic_mcp_oauth_url_allowed("https://auth.example.com/authorize", err, sizeof err) == 0, "https allowed");
    expect(pic_mcp_oauth_url_allowed("http://127.0.0.1:8080/token", err, sizeof err) == 0, "http 127.0.0.1 allowed");
    expect(pic_mcp_oauth_url_allowed("http://localhost:3000/token", err, sizeof err) == 0, "http localhost allowed");
    expect(pic_mcp_oauth_url_allowed("http://[::1]:3000/token", err, sizeof err) == 0, "http ::1 allowed");
    expect(pic_mcp_oauth_url_allowed("http://auth.example.com/token", err, sizeof err) == -1, "remote http rejected");
    expect(pic_mcp_oauth_url_allowed("file:///etc/passwd", err, sizeof err) == -1, "file:// rejected");
    expect(pic_mcp_oauth_url_allowed("javascript:alert(1)", err, sizeof err) == -1, "javascript: rejected");
    expect(pic_mcp_oauth_url_allowed("https://user:[email protected]/t", err, sizeof err) == -1, "userinfo rejected");

    /* Callback guard */
    expect(pic_mcp_oauth_callback_allowed("http://127.0.0.1/callback", err, sizeof err) == 0, "default callback ok");
    expect(pic_mcp_oauth_callback_allowed("http://localhost:9999/oauth/cb", err, sizeof err) == 0, "localhost callback ok");
    expect(pic_mcp_oauth_callback_allowed("https://127.0.0.1/callback", err, sizeof err) == -1, "https callback rejected");
    expect(pic_mcp_oauth_callback_allowed("http://evil.example/callback", err, sizeof err) == -1, "remote callback rejected");
    expect(pic_mcp_oauth_callback_allowed("http://127.0.0.1/cb?x=1", err, sizeof err) == -1, "query callback rejected");
}

static void test_resource_and_iss(void) {
    char err[256];

    /* RFC 8707 resource check */
    expect(pic_mcp_oauth_resource_matches("https://api.example.com/mcp", "https://api.example.com/mcp", err, sizeof err) == 0,
           "exact resource match");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com/mcp/v1", "https://api.example.com/mcp", err, sizeof err) == 0,
           "path prefix resource match");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com/mcp", "https://api.example.com/", err, sizeof err) == 0,
           "root resource covers subpath");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com:443/mcp", "https://API.EXAMPLE.COM/mcp/", err, sizeof err) == 0,
           "default port and case match");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com/mcp2", "https://api.example.com/mcp", err, sizeof err) == -1,
           "sibling path /mcp2 does not match /mcp");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com/mcp", "https://other.example.com/mcp", err, sizeof err) == -1,
           "different host rejected");
    expect(pic_mcp_oauth_resource_matches("https://api.example.com:8443/mcp", "https://api.example.com/mcp", err, sizeof err) == -1,
           "different port rejected");

    /* RFC 9207 iss check */
    expect(pic_mcp_oauth_check_iss(NULL, "https://auth.example.com", 0, err, sizeof err) == 0, "absent iss ok when unsupported");
    expect(pic_mcp_oauth_check_iss(NULL, "https://auth.example.com", 1, err, sizeof err) == -1,
           "absent iss rejected when advertised");
    expect(pic_mcp_oauth_check_iss("https://auth.example.com", "https://auth.example.com", 1, err, sizeof err) == 0,
           "matching iss ok");
    expect(pic_mcp_oauth_check_iss("https://evil.example.com", "https://auth.example.com", 0, err, sizeof err) == -1,
           "mismatching iss rejected even when unadvertised");
    expect(pic_mcp_oauth_check_iss("https://auth.example.com", "", 0, err, sizeof err) == -1,
           "present iss rejected when no metadata issuer");
}

static void test_scope_and_cfg(void) {
    char out[256], err[256], *json;
    pic_mcp_oauth_cfg cfg, back;

    expect(pic_mcp_oauth_step_up_scope("mcp:base mcp:read", "mcp:read mcp:list", "mcp:write mcp:base", out, sizeof out) > 0,
           "step-up scope built");
    expect(strcmp(out, "mcp:base mcp:read mcp:list mcp:write") == 0, "dedup union preserves order");

    expect(pic_mcp_oauth_step_up_scope(NULL, "  a   b ", "b c", out, sizeof out) > 0 && strcmp(out, "a b c") == 0,
           "extra whitespace and NULL handled");

    memset(&cfg, 0, sizeof cfg);
    (void)snprintf(cfg.client_id, sizeof cfg.client_id, "cid-1");
    (void)snprintf(cfg.callback_url, sizeof cfg.callback_url, "http://localhost:8765/cb");
    cfg.callback_port = 8765;
    (void)snprintf(cfg.scope, sizeof cfg.scope, "read write");
    (void)snprintf(cfg.client_name, sizeof cfg.client_name, "pic-test");
    (void)snprintf(cfg.auth_server_metadata_url, sizeof cfg.auth_server_metadata_url,
                   "https://auth.example.com/.well-known/oauth-authorization-server");
    cfg.has_client_secret = 1;
    json = pic_mcp_oauth_cfg_json(&cfg);
    expect(json != NULL, "cfg serialized");
    expect(json && strstr(json, "clientSecret\"") == NULL, "cfg JSON never has clientSecret");
    expect(pic_mcp_oauth_cfg_parse(json, &back, err, sizeof err) == 0, "cfg parsed back");
    expect(strcmp(back.client_id, "cid-1") == 0 && back.callback_port == 8765 && back.has_client_secret == 1 &&
               strcmp(back.callback_url, "http://localhost:8765/cb") == 0 &&
               strcmp(back.scope, "read write") == 0 && strcmp(back.client_name, "pic-test") == 0 &&
               strcmp(back.auth_server_metadata_url, cfg.auth_server_metadata_url) == 0,
           "cfg round-trip matches");
    free(json);

    expect(pic_mcp_oauth_cfg_parse("{\"callbackPort\":99999}", &back, err, sizeof err) == -1, "bad callbackPort rejected");
    expect(pic_mcp_oauth_cfg_parse("{\"authServerMetadataUrl\":\"http://remote.example/m\"}", &back, err, sizeof err) == -1,
           "insecure authServerMetadataUrl rejected");
}

static const char *test_pass;
static const pic_platform *orig_plat;

static int fake_secret_key(const struct pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                           size_t errcap) {
    if (strcmp(ask->source, "passphrase") == 0) {
        size_t n = strlen(test_pass);
        if (n > cap) {
            return -1;
        }
        memcpy(buf, test_pass, n);
        *len = n;
        *how = PIC_SECRET_PASSPHRASE;
        return 0;
    }
    return orig_plat->secret_key(ask, buf, cap, len, how, err, errcap);
}

static int file_contains(const char *path, const char *needle) {
    FILE *f = fopen(path, "rb");
    char *buf;
    long n;
    int found = 0;
    size_t nn = strlen(needle);
    if (!f) {
        return 0;
    }
    if (fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) > 0 && fseek(f, 0, SEEK_SET) == 0 && (buf = malloc((size_t)n))) {
        if (fread(buf, 1, (size_t)n, f) == (size_t)n) {
            for (long i = 0; i + (long)nn <= n; i++) {
                if (memcmp(buf + i, needle, nn) == 0) {
                    found = 1;
                    break;
                }
            }
        }
        free(buf);
    }
    fclose(f);
    return found;
}

static void test_rekey_and_reset(void) {
    char err[256] = "", src[32] = "", dbpath[512], long_url[420], key[600];
    int skipped = -1, rc;
    sqlite3 *db;
    sqlite3_stmt *q = NULL;
    pic_platform p;

    /* Build a >300-byte URL to verify pic_cred_rekey handles long mcp-oauth server_keys. */
    (void)snprintf(long_url, sizeof long_url, "https://mcp.example.com/");
    while (strlen(long_url) < 320) {
        (void)snprintf(long_url + strlen(long_url), sizeof long_url - strlen(long_url), "segment/");
    }

    expect(pic_cred_rekey("file", src, sizeof src, &skipped, err, sizeof err) == 0, "new file-key store created");
    expect(pic_mcp_oauth_save_secret("long-srv", long_url, "SUPER_SECRET_MCP_CLIENT_999", err, sizeof err) == 0,
           "save_secret seals into picu_mcp_oauth");

    expect(pic_userdb_path(dbpath, sizeof dbpath) == 0, "userdb path");
    expect(!file_contains(dbpath, "SUPER_SECRET_MCP_CLIENT_999"), "clientSecret never stored in plaintext in pic.sqlite");

    /* Rekey from file -> passphrase and verify skipped == 0 and row still unboxes cleanly. */
    orig_plat = pic_platform_get();
    p = *orig_plat;
    p.secret_key = fake_secret_key;
    test_pass = "mcp-rekey-passphrase-1";
    pic_platform_set(&p);
    skipped = -1;
    rc = pic_cred_rekey("passphrase", src, sizeof src, &skipped, err, sizeof err);
    expect(rc == 0 && skipped == 0, "pic_cred_rekey resealed picu_mcp_oauth with 0 skipped");

    /* Lock, unlock with passphrase, and verify we can unbox the long-key row. */
    pic_cred_lock();
    expect(pic_cred_unlock(err, sizeof err) == 0, "unlock with new passphrase");
    expect(pic_mcp_oauth_server_key("long-srv", long_url, key, sizeof key) > 0, "key computed");
    db = pic_userdb(err, sizeof err);
    expect(db != NULL, "userdb open");
    if (db && sqlite3_prepare_v2(db, "SELECT sealed FROM picu_mcp_oauth WHERE server_key = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            const unsigned char *blob = sqlite3_column_blob(q, 0);
            int bn = sqlite3_column_bytes(q, 0);
            char aad[700], plain[1024];
            memset(plain, 0, sizeof plain);
            (void)snprintf(aad, sizeof aad, "mcp-oauth:%s", key);
            expect(bn > PIC_CRED_OVERHEAD && pic_cred_unbox(aad, blob, (size_t)bn, plain, err, sizeof err) == 0,
                   "rekeyed picu_mcp_oauth row unboxes under new master key");
            expect(strstr(plain, "SUPER_SECRET_MCP_CLIENT_999") != NULL, "rekeyed row preserves clientSecret");
            pic_cred_wipe(plain, sizeof plain);
        } else {
            expect(0, "rekeyed picu_mcp_oauth row missing");
        }
    }
    sqlite3_finalize(q);

    /* Logout removes the row; save again then test pic_cred_reset clears picu_mcp_oauth. */
    expect(pic_mcp_oauth_logout("long-srv", long_url, err, sizeof err) == 1, "logout removes row");
    expect(pic_mcp_oauth_logout("long-srv", long_url, err, sizeof err) == 0, "second logout reports 0");

    expect(pic_mcp_oauth_save_secret("long-srv", long_url, "ANOTHER_SECRET", err, sizeof err) == 0, "re-save secret");
    expect(pic_cred_reset(err, sizeof err) == 0, "pic_cred_reset succeeds");
    if (db && sqlite3_prepare_v2(db, "SELECT count(*) FROM picu_mcp_oauth", -1, &q, NULL) == SQLITE_OK) {
        expect(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) == 0, "pic_cred_reset empties picu_mcp_oauth");
    }
    sqlite3_finalize(q);
    pic_platform_set(orig_plat);
}

int main(void) {
    test_www_auth();
    test_server_key_and_urls();
    test_resource_and_iss();
    test_scope_and_cfg();
    test_rekey_and_reset();
    if (failures == 0) {
        puts("PASS: MCP OAuth unit tests (parsers, normalization, guards, rekey, reset)");
    }
    return failures != 0;
}