Skip to content
pi-c Documentation
Login

Documentation

/* Subscription sign-in below the terminal: the shared OAuth helpers, the
 * loopback callback (a bad state and a wrong path refused, then the real
 * redirect taken once), a pasted redirect, the RFC 8628 device poll against
 * fake_oauth, and the credential store's oauth rows: an old table rebuilt
 * for the new kind, a sign-in sealed, its access token served, refreshed
 * near expiry and after a refusal, and left alone when another process got
 * there first. HOME must be a private directory; FAKE_OAUTH names the fake
 * server; argv[1] is the SSE file it serves. */
#include <arpa/inet.h>
#include <assert.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "cred.h"
#include "oauth.h"
#include "platform.h"
#include "userdb.h"

static int refreshes;
static char server[64];

static int test_secret(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                       size_t errcap) {
    (void)ask;
    (void)cap;
    (void)err;
    (void)errcap;
    memcpy(buf, "oauth test", 10);
    *len = 10;
    *how = PIC_SECRET_PASSPHRASE;
    return 0;
}

static void test_helpers(void) {
    char v[64], c[64], *p, *f;
    const char *pairs[] = {"a", "x y&z", "skip", NULL, "b", "~ok-._", NULL};
    assert(pic_oauth_same("abc", "abc") && !pic_oauth_same("abc", "abd") && !pic_oauth_same("abc", "ab") &&
           !pic_oauth_same("", "a") && pic_oauth_same("", ""));
    f = pic_oauth_form(pairs);
    assert(f && strcmp(f, "a=x%20y%26z&b=~ok-._") == 0);
    p = pic_oauth_param(f, "a");
    assert(p && strcmp(p, "x y&z") == 0);
    free(p);
    assert(pic_oauth_param(f, "skip") == NULL && pic_oauth_param("ab=1", "a") == NULL);
    p = pic_oauth_param("x=1&state=a%2Bb+c", "state");
    assert(p && strcmp(p, "a+b c") == 0);
    free(p);
    free(f);
    assert(pic_oauth_pkce(v, c) == 0 && strlen(v) == 43 && strlen(c) == 43 && strcmp(v, c) != 0);
    assert(strspn(v, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") == 43);
    puts("ok helpers: constant-time compare, form encoding, query decoding, PKCE shape");
}

/* A browser stand-in: GETs TARGET from 127.0.0.1:PORT, the reply's status into *status. */
static void browse(int port, const char *target, int *status) {
    struct sockaddr_in a;
    char req[1024], resp[2048];
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    ssize_t n, got = 0;
    memset(&a, 0, sizeof a);
    a.sin_family = AF_INET;
    a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    a.sin_port = htons((unsigned short)port);
    assert(fd >= 0 && connect(fd, (struct sockaddr *)&a, sizeof a) == 0);
    n = snprintf(req, sizeof req, "GET %s HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", target);
    assert(send(fd, req, (size_t)n, 0) == n);
    while ((n = recv(fd, resp + got, sizeof resp - 1 - (size_t)got, 0)) > 0) {
        got += n;
    }
    resp[got] = '\0';
    close(fd);
    *status = got > 12 ? atoi(resp + 9) : 0;
}

static void test_callback(void) {
    pic_oauth_callback cb;
    pic_oauth_io io = {stdout, -1, PIC_CRED_NO_BROWSER, 0};
    char err[256], *query = NULL, *pasted = NULL;
    int fds[2];
    pid_t pid;
    assert(pic_oauth_listen(&cb, 0, "/auth/callback", "good-state", err, sizeof err) == 0 && cb.port > 0);
    assert(pipe(fds) == 0);
    pid = fork();
    if (pid == 0) { /* the browser: three wrong visits, then the real redirect */
        int st[4];
        browse(cb.port, "/auth/callback?code=c1&state=bad-state", &st[0]);
        browse(cb.port, "/elsewhere?code=c1&state=good-state", &st[1]);
        browse(cb.port, "/auth/callback?state=good-state", &st[2]);
        browse(cb.port, "/auth/callback?code=c2&state=good-state&client_id=cid", &st[3]);
        _exit(st[0] == 400 && st[1] == 404 && st[2] == 400 && st[3] == 200 ? 0 : 1);
    }
    assert(pic_oauth_wait(&cb, &io, 20, &query, &pasted, err, sizeof err) == 0);
    assert(query && !pasted && strstr(query, "code=c2") && strstr(query, "client_id=cid"));
    {
        int status;
        assert(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0);
    }
    free(query);
    pic_oauth_close(&cb);
    puts("ok callback: a bad state, a wrong path and a missing code are refused; the redirect is taken");

    /* A provider's error ends the wait. */
    assert(pic_oauth_listen(&cb, 0, "/cb", "s", err, sizeof err) == 0);
    if ((pid = fork()) == 0) {
        int st;
        browse(cb.port, "/cb?error=access_denied&error_description=%1B%5D0%3Bowned%07&state=s", &st);
        _exit(st == 400 ? 0 : 1);
    }
    /* The provider's words reach the terminal with no control byte left in them. */
    assert(pic_oauth_wait(&cb, &io, 20, &query, &pasted, err, sizeof err) == -1 && strstr(err, "access_denied") &&
           strstr(err, "?]0;owned?") && !strchr(err, '\x1b') && !strchr(err, '\a'));
    (void)waitpid(pid, NULL, 0);
    pic_oauth_close(&cb);

    /* A connection left idle (a browser's spare one, a stray local program) is dropped within about a
     * second, so it cannot hold up the redirect behind it; a taken port is told apart. */
    assert(pic_oauth_listen(&cb, 0, "/cb", "s", err, sizeof err) == 0);
    {
        pic_oauth_callback again;
        assert(pic_oauth_listen(&again, cb.port, "/cb", "s", err, sizeof err) == -2 && strstr(err, "in use"));
    }
    if ((pid = fork()) == 0) {
        struct sockaddr_in sa;
        int idle = socket(AF_INET, SOCK_STREAM, 0), st;
        struct timespec t = {0, 100000000};
        memset(&sa, 0, sizeof sa);
        sa.sin_family = AF_INET;
        sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        sa.sin_port = htons((unsigned short)cb.port);
        if (connect(idle, (struct sockaddr *)&sa, sizeof sa) != 0) {
            _exit(1);
        }
        nanosleep(&t, NULL);
        browse(cb.port, "/cb?code=c3&state=s", &st);
        close(idle);
        _exit(st == 200 ? 0 : 1);
    }
    {
        struct timespec t0, t1;
        int status;
        clock_gettime(CLOCK_MONOTONIC, &t0);
        assert(pic_oauth_wait(&cb, &io, 20, &query, &pasted, err, sizeof err) == 0 && strstr(query, "code=c3"));
        clock_gettime(CLOCK_MONOTONIC, &t1);
        assert(t1.tv_sec - t0.tv_sec < 3); /* not the 5 s a whole connection gets */
        assert(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0);
        free(query);
    }
    pic_oauth_close(&cb);
    puts("ok callback: an idle connection is dropped fast; a taken port is reported as taken");

    /* A pasted line wins when no browser comes; a timeout ends a wait with neither. */
    io.in = fds[0];
    assert(write(fds[1], "  http://127.0.0.1:1/cb?code=p&state=s \n", 40) == 40);
    assert(pic_oauth_wait(NULL, &io, 5, &query, &pasted, err, sizeof err) == 0 && pasted &&
           strcmp(pasted, "http://127.0.0.1:1/cb?code=p&state=s") == 0);
    assert(pic_oauth_pasted_query(pasted, "http://127.0.0.1:1/cb", "s", &query, err, sizeof err) == 0 &&
           strcmp(query, "code=p&state=s") == 0);
    free(query);
    assert(pic_oauth_pasted_query(pasted, "http://127.0.0.1:1/cb", "t", &query, err, sizeof err) == -1 &&
           strstr(err, "state mismatch"));
    assert(pic_oauth_pasted_query("code=p", "http://127.0.0.1:1/cb", "s", &query, err, sizeof err) == -1 &&
           strstr(err, "starts with"));
    free(pasted);
    assert(pic_oauth_listen(&cb, 0, "/cb", "s", err, sizeof err) == 0);
    assert(pic_oauth_wait(&cb, &io, 1, &query, &pasted, err, sizeof err) == -1 && strstr(err, "timed out"));
    pic_oauth_close(&cb);
    close(fds[0]);
    close(fds[1]);
    puts("ok paste: a pasted redirect is read, its state checked; a wait times out");
}

static void test_device(void) {
    pic_oauth_io io = {stdout, -1, PIC_CRED_NO_BROWSER, 0};
    char dev[128], tok[128], err[256], *token = NULL, *access;
    const char *pairs[] = {"client_id", "issued-client-7", "scope", "openid", NULL};
    char *form = pic_oauth_form(pairs);
    (void)snprintf(dev, sizeof dev, "%s/device/code", server);
    (void)snprintf(tok, sizeof tok, "%s/device/token", server);
    assert(pic_oauth_device(&io, dev, tok, form, "issued-client-7", &token, err, sizeof err) == 0);
    access = pic_oauth_json_text(token, "$.access_token");
    assert(access && strncmp(access, "acc-", 4) == 0);
    free(access);
    free(token);
    free(form);
    puts("ok device code: pending, slow_down, then the grant");
}

/* ---- the store's oauth rows --------------------------------------------- */

static long long now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

static char next_cred[512];

static const char *t_label(const char *provider) { return strcmp(provider, "acme") == 0 ? "Sign in with Acme" : NULL; }

static int t_login(const char *provider, int flags, const char **kind, char **secret, char *err, size_t errcap) {
    (void)provider;
    (void)flags;
    (void)err;
    (void)errcap;
    *kind = "oauth";
    *secret = strdup(next_cred);
    return 0;
}

static int t_refresh(const char *provider, const char *cred, char **out, char *err, size_t errcap) {
    char buf[512];
    (void)provider;
    if (!strstr(cred, "\"refresh\":\"r1\"")) {
        (void)snprintf(err, errcap, "invalid_grant");
        return -1;
    }
    refreshes++;
    (void)snprintf(buf, sizeof buf, "{\"access\":\"acc-fresh-%d\",\"refresh\":\"r1\",\"expires\":%lld}", refreshes,
                   now_ms() + 3600000);
    *out = strdup(buf);
    return 0;
}

static const pic_cred_oauth_ops t_ops = {t_label, t_login, t_refresh, NULL};

static int kinds(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
    (void)created_ms;
    (void)used_ms;
    strcat(ctx, name);
    strcat(ctx, "=");
    strcat(ctx, kind);
    strcat(ctx, ",");
    return 0;
}

static void test_store(void) {
    pic_platform p = *pic_platform_host();
    char key[PIC_CRED_TOKEN_CAP], err[512], list[256] = "";
    p.secret_key = test_secret;
    p.secret_keep = NULL; /* a passphrase store */
    pic_platform_set(&p);
    pic_cred_oauth_register(&t_ops);
    assert(pic_cred_oauth_label("acme") && !pic_cred_oauth_label("other"));
    assert(pic_cred_oauth_login("other", 0, err, sizeof err) == -1 && strstr(err, "no subscription sign-in"));

    /* A sign-in whose token is good for an hour: served as it is. */
    (void)snprintf(next_cred, sizeof next_cred, "{\"access\":\"acc-first\",\"refresh\":\"r1\",\"expires\":%lld,\"x\":1}",
                   now_ms() + 3600000);
    assert(pic_cred_oauth_login("acme", 0, err, sizeof err) == 0);
    assert(pic_cred_source_of("acme", "ACME_KEY_UNSET", "") == PIC_CRED_STORED_OAUTH);
    assert(pic_cred_get("acme", "ACME_KEY_UNSET", "", key, sizeof key, err, sizeof err) == 0 && strcmp(key, "acc-first") == 0);
    assert(refreshes == 0);
    assert(pic_cred_each(kinds, list) == 0 && strstr(list, "acme=oauth,"));

    /* Another process already replaced the refused token: no refresh, the new one. */
    assert(pic_cred_refresh("acme", "acc-something-older", key, sizeof key, err, sizeof err) == 0 &&
           strcmp(key, "acc-first") == 0 && refreshes == 0);
    /* The refused token is the stored one: refreshed, written back. */
    assert(pic_cred_refresh("acme", "acc-first", key, sizeof key, err, sizeof err) == 0 && strcmp(key, "acc-fresh-1") == 0);
    assert(refreshes == 1);
    assert(pic_cred_get("acme", "", "", key, sizeof key, err, sizeof err) == 0 && strcmp(key, "acc-fresh-1") == 0);

    /* Near expiry: refreshed before use. */
    (void)snprintf(next_cred, sizeof next_cred, "{\"access\":\"acc-old\",\"refresh\":\"r1\",\"expires\":%lld}", now_ms() + 30000);
    assert(pic_cred_oauth_login("acme", 0, err, sizeof err) == 0);
    assert(pic_cred_get("acme", "", "", key, sizeof key, err, sizeof err) == 0 && strcmp(key, "acc-fresh-2") == 0);
    assert(refreshes == 2);

    /* Near expiry, the early refresh fails (a dropped connection): the access token is still
     * good, so it is served rather than the request failing. */
    (void)snprintf(next_cred, sizeof next_cred, "{\"access\":\"acc-near\",\"refresh\":\"r-offline\",\"expires\":%lld}",
                   now_ms() + 30000);
    assert(pic_cred_oauth_login("acme", 0, err, sizeof err) == 0);
    assert(pic_cred_get("acme", "", "", key, sizeof key, err, sizeof err) == 0 && strcmp(key, "acc-near") == 0);

    /* A refresh the provider refuses: an error naming the sign-in, no token in it. */
    (void)snprintf(next_cred, sizeof next_cred, "{\"access\":\"acc-dead\",\"refresh\":\"r-revoked\",\"expires\":%lld}", now_ms());
    assert(pic_cred_oauth_login("acme", 0, err, sizeof err) == 0);
    assert(pic_cred_get("acme", "", "", key, sizeof key, err, sizeof err) == -1);
    assert(strstr(err, "pic auth login acme") && strstr(err, "invalid_grant") && !strstr(err, "acc-dead") &&
           !strstr(err, "r-revoked"));

    /* The stored sign-in beats the environment (Pi's order); once logout removes the row the
     * environment is what is left. */
    setenv("ACME_KEY_SET", "sk-env", 1);
    assert(pic_cred_source_of("acme", "ACME_KEY_SET", "") == PIC_CRED_STORED_OAUTH);
    assert(pic_cred_logout("acme") == 1 && pic_cred_source_of("acme", "", "") == PIC_CRED_NONE);
    assert(pic_cred_source_of("acme", "ACME_KEY_SET", "") == PIC_CRED_ENV);

    /* A sign-in without a refresh token is refused before it is stored. */
    (void)snprintf(next_cred, sizeof next_cred, "{\"access\":\"a\",\"expires\":1}");
    assert(pic_cred_oauth_login("acme", 0, err, sizeof err) == -1 && !pic_cred_stored("acme"));
    puts("ok store: an oauth row sealed, served, refreshed near expiry and on a stale token, skipped when replaced");
}

/* A pic.sqlite from before 'oauth' was a kind: its key survives, and an oauth row can be written. */
static void test_migration(void) {
    char path[4096], err[256];
    sqlite3 *db;
    assert(pic_userdb_path(path, sizeof path) == 0);
    {
        char dir[4096];
        (void)snprintf(dir, sizeof dir, "%s/.pic", getenv("HOME"));
        (void)mkdir(dir, 0700);
    }
    assert(sqlite3_open(path, &db) == SQLITE_OK);
    assert(sqlite3_exec(db,
                        "CREATE TABLE picu_credential(name TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('api_key')),"
                        " sealed BLOB NOT NULL, created_ms INTEGER NOT NULL, used_ms INTEGER);"
                        "INSERT INTO picu_credential VALUES('old', 'api_key', x'00', 1, NULL);",
                        NULL, NULL, NULL) == SQLITE_OK);
    sqlite3_close(db);
    db = pic_userdb(err, sizeof err);
    assert(db);
    assert(pic_cred_stored("old"));
    assert(sqlite3_exec(db, "INSERT INTO picu_credential VALUES('new', 'oauth', x'00', 2, NULL);"
                            "DELETE FROM picu_credential;",
                        NULL, NULL, NULL) == SQLITE_OK);
    puts("ok migration: an old credential table takes the oauth kind and keeps its rows");
}

int main(int argc, char **argv) {
    const char *fake = getenv("FAKE_OAUTH");
    char dir[] = "/tmp/pic-test-oauth.XXXXXX", portfile[256], cmd_deadline[] = "60";
    pid_t spid;
    FILE *f;
    int port = 0;
    assert(argc == 2 && fake && mkdtemp(dir));
    test_migration();
    test_helpers();
    test_callback();
    (void)snprintf(portfile, sizeof portfile, "%s/port", dir);
    if ((spid = fork()) == 0) {
        execl(fake, fake, portfile, dir, cmd_deadline, argv[1], (char *)NULL);
        _exit(127);
    }
    for (int i = 0; i < 400 && !port; i++) {
        struct timespec t = {0, 25000000};
        if ((f = fopen(portfile, "r"))) {
            if (fscanf(f, "%d", &port) != 1) {
                port = 0;
            }
            fclose(f);
        }
        nanosleep(&t, NULL);
    }
    assert(port > 0);
    (void)snprintf(server, sizeof server, "http://127.0.0.1:%d", port);
    test_device();
    test_store();
    kill(spid, SIGTERM);
    (void)waitpid(spid, NULL, 0);
    {
        char rm[300];
        (void)snprintf(rm, sizeof rm, "rm -rf %s", dir);
        assert(system(rm) == 0);
    }
    puts("PASS: test_oauth");
    return 0;
}