Skip to content
pi-c Documentation
Login

Documentation

/* Web Push (src/webpush.c): the protocol's VAPID and topic vectors (remote-protocol section 8,
 * vector 4 and vector 5's topic), the endpoint check, and sends to fake_server, whose
 * saved requests are checked here as the push service would: the headers, the token's signature
 * and claims, and the body decrypted with the phone's key.
 *
 * Usage: test_webpush FAKE_SERVER WORK_DIR */
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "bearssl.h"
#include "noise.h"
#include "webpush.h"

typedef unsigned char u8;

static void fill(u8 *b, int from) {
    for (int i = 0; i < 32; i++) {
        b[i] = (u8)(from + i);
    }
}

static size_t unhex(const char *s, u8 *out) {
    size_t n = 0;
    for (; s[0] && s[1]; s += 2) {
        unsigned v;
        assert(sscanf(s, "%2x", &v) == 1);
        out[n++] = (u8)v;
    }
    return n;
}

static int b64v(int c) {
    return c >= 'A' && c <= 'Z' ? c - 'A'
           : c >= 'a' && c <= 'z' ? c - 'a' + 26
           : c >= '0' && c <= '9' ? c - '0' + 52
           : c == '-'             ? 62
           : c == '_'             ? 63
                                  : -1;
}

/* base64url without padding; the decoded length. */
static size_t unb64(const char *s, size_t n, u8 *out) {
    size_t o = 0;
    unsigned acc = 0;
    int bits = 0;
    for (size_t i = 0; i < n; i++) {
        int v = b64v((unsigned char)s[i]);
        assert(v >= 0);
        acc = (acc << 6) | (unsigned)v;
        bits += 6;
        if (bits >= 8) {
            bits -= 8;
            out[o++] = (u8)(acc >> bits);
        }
    }
    return o;
}

static void b64(const u8 *in, size_t n, char *out) {
    static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    size_t o = 0;
    unsigned acc = 0;
    int bits = 0;
    for (size_t i = 0; i < n; i++) {
        acc = (acc << 8) | in[i];
        bits += 8;
        while (bits >= 6) {
            bits -= 6;
            out[o++] = a[(acc >> bits) & 63];
        }
    }
    if (bits > 0) {
        out[o++] = a[(acc << (6 - bits)) & 63];
    }
    out[o] = '\0';
}

/* ---- the vectors (scratchpad rcvec/vectors.json, groups vapid, push, rfc8291_appendix_a) ---- */

#define VAPID_PUB "BL5Xe1szuMPc-oGFhZPYSTggPni6EPh_t1N27qk31Vkq9SvcZBxDreqeNC_8b9v-XIY8n27TBHGZmh0B7PVAZb4"
#define VAPID_JWT                                                                                                      \
    "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwczovL3B1c2guZXhhbXBsZS5uZXQiLCJleHAiOjE4MDAwMDAwMDAsInN1YiI6" \
    "Imh0dHBzOi8vcmVsYXkuZXhhbXBsZSJ9.hXKTS04fGGvcEhgc-dxQ7zRPIS3lEaDDLLZETwz67htYyaf4z21OQ2_yW-t5Gm7kZVvECcWCZei9TZ8t_" \
    "3OmSA"

static void pubkey(const u8 priv[32], u8 pub[65]) {
    pic_noise_keypair k;
    assert(pic_noise_keypair_make(&k, priv) == 0);
    memcpy(pub, k.pub, 65);
}

static void test_vapid(void) {
    u8 priv[32], pub[65];
    char k[96], auth[512];
    int n;
    fill(priv, 0x51);
    pubkey(priv, pub);
    b64(pub, 65, k);
    assert(strcmp(k, VAPID_PUB) == 0);
    n = pic_webpush_authorization(priv, "https://push.example.net", 1800000000, "https://relay.example", auth, sizeof auth);
    assert(n > 0 && (size_t)n == strlen(auth));
    assert(strcmp(auth, "vapid t=" VAPID_JWT ", k=" VAPID_PUB) == 0);
    /* Too small a buffer, a claim JSON would escape, a scalar that is zero. */
    assert(pic_webpush_authorization(priv, "https://push.example.net", 1800000000, "https://relay.example", auth,
                                     (size_t)n) == -1);
    assert(pic_webpush_authorization(priv, "https://a\".example", 1800000000, "https://relay.example", auth,
                                     sizeof auth) == -1);
    assert(pic_webpush_authorization(priv, "https://a.example", 1800000000, "https://relay\\.example", auth,
                                     sizeof auth) == -1);
    assert(pic_webpush_authorization(priv, "https://a.example\n", 1800000000, "https://relay.example", auth,
                                     sizeof auth) == -1);
    memset(priv, 0, sizeof priv);
    assert(pic_webpush_authorization(priv, "https://a.example", 1, "https://relay.example", auth, sizeof auth) == -1);
    memset(priv, 0xff, sizeof priv); /* not below the group order */
    assert(pic_webpush_authorization(priv, "https://a.example", 1, "https://relay.example", auth, sizeof auth) == -1);
}

#define PUSH_PT "{\"v\":1,\"title\":\"pi-c\",\"body\":\"Done: all 41 tests pass.\",\"session\":\"w1/c1\",\"seq\":42}"

/* The push body and RFC 8291 appendix A are noise.c's, tested in test_noise.c; the topic is here. */
static void test_topic(void) {
    u8 auth[16];
    char topic[PIC_WEBPUSH_TOPIC];
    assert(unhex("000102030405060708090a0b0c0d0e0f", auth) == 16);
    pic_webpush_topic(auth, "w1/c1", topic);
    assert(strcmp(topic, "pVsNmpujVOLy-pKpnsA2GA") == 0);
}

static void test_endpoint(void) {
    char o[128];
    assert(pic_webpush_endpoint_ok("https://fcm.googleapis.com/fcm/send/abc:def"));
    assert(pic_webpush_endpoint_ok("https://updates.push.services.mozilla.com:443/wpush/v2/x"));
    assert(pic_webpush_endpoint_ok("https://web.push.apple.com/QH1"));
    assert(!pic_webpush_endpoint_ok("http://fcm.googleapis.com/fcm/send/x"));
    assert(!pic_webpush_endpoint_ok("https://fcm.googleapis.com:8443/x"));
    assert(!pic_webpush_endpoint_ok("https://192.168.1.2/x"));
    assert(!pic_webpush_endpoint_ok("https://[::1]/x"));
    assert(!pic_webpush_endpoint_ok("https://10.0.0.1:443/x"));
    assert(!pic_webpush_endpoint_ok("https://[email protected]/x"));
    assert(!pic_webpush_endpoint_ok("https:///x"));
    assert(!pic_webpush_endpoint_ok("https://push.example:/x"));
    assert(!pic_webpush_endpoint_ok("https://push..example/x"));
    assert(!pic_webpush_endpoint_ok("https://push.example/x\r\nX-Evil: 1"));
    assert(!pic_webpush_endpoint_ok("https://push.example/a b"));
    assert(!pic_webpush_endpoint_ok("ftp://push.example/x"));
    assert(pic_webpush_origin("https://push.example.net/a/b", o, sizeof o) == 24 && strcmp(o, "https://push.example.net") == 0);
    assert(pic_webpush_origin("https://push.example.net:443/a", o, sizeof o) > 0 && strcmp(o, "https://push.example.net") == 0);
    assert(pic_webpush_origin("https://Push.Example.NET", o, sizeof o) > 0 && strcmp(o, "https://push.example.net") == 0);
    assert(pic_webpush_origin("http://127.0.0.1:8080/p", o, sizeof o) > 0 && strcmp(o, "http://127.0.0.1:8080") == 0);
    assert(pic_webpush_origin("http://127.0.0.1:80/p", o, sizeof o) > 0 && strcmp(o, "http://127.0.0.1") == 0);
    assert(pic_webpush_origin("https://push.example.net/a", o, 10) == -1);
    assert(pic_webpush_origin("push.example.net/a", o, sizeof o) == -1);
}

/* ---- sends to fake_server ---- */

static pid_t server;
static char logdir[1024];

static int start_server(const char *bin, const char *work, char *const *specs, int nspecs) {
    static char binpath[1024], portfile[1100], deadline[] = "60";
    char *argv[32];
    int port = 0;
    (void)snprintf(portfile, sizeof portfile, "%s/port", work);
    (void)snprintf(logdir, sizeof logdir, "%s/log", work);
    unlink(portfile);
    (void)snprintf(binpath, sizeof binpath, "%s", bin);
    argv[0] = binpath;
    argv[1] = portfile;
    argv[2] = logdir;
    argv[3] = deadline;
    for (int i = 0; i < nspecs; i++) {
        argv[4 + i] = specs[i];
    }
    argv[4 + nspecs] = NULL;
    server = fork();
    assert(server >= 0);
    if (server == 0) {
        execv(binpath, argv);
        _exit(127);
    }
    for (int i = 0; i < 200 && port == 0; i++) {
        FILE *f = fopen(portfile, "r");
        if (f) {
            if (fscanf(f, "%d", &port) != 1) {
                port = 0;
            }
            fclose(f);
        }
        if (port == 0) {
            struct timespec t = {0, 25 * 1000000L};
            nanosleep(&t, NULL);
        }
    }
    assert(port > 0);
    return port;
}

static void stop_server(void) {
    int st;
    kill(server, SIGTERM);
    (void)waitpid(server, &st, 0);
}

static char *slurp(const char *path, size_t *len) {
    FILE *f = fopen(path, "rb");
    char *buf;
    long n;
    assert(f);
    assert(fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) >= 0 && fseek(f, 0, SEEK_SET) == 0);
    buf = malloc((size_t)n + 1);
    assert(buf && fread(buf, 1, (size_t)n, f) == (size_t)n);
    fclose(f);
    buf[n] = '\0';
    *len = (size_t)n;
    return buf;
}

/* The value of header NAME (exact case, as webpush.c sends it) in the request head, or NULL. */
static const char *header(const char *req, const char *name, char *out, size_t cap) {
    char want[64];
    const char *p, *end = strstr(req, "\r\n\r\n");
    (void)snprintf(want, sizeof want, "\r\n%s: ", name);
    p = strstr(req, want);
    if (!p || p > end) {
        return NULL;
    }
    p += strlen(want);
    (void)snprintf(out, cap, "%.*s", (int)(strstr(p, "\r\n") - p), p);
    return out;
}

static void hmac(u8 out[32], const u8 *k, size_t kn, const void *a, size_t an, const void *b, size_t bn) {
    br_hmac_key_context kc;
    br_hmac_context c;
    br_hmac_key_init(&kc, &br_sha256_vtable, k, kn);
    br_hmac_init(&c, &kc, 0);
    br_hmac_update(&c, a, an);
    br_hmac_update(&c, b, bn);
    br_hmac_out(&c, out);
}

/* The phone's side of RFC 8291: the plaintext's length in PT, or -1 when the body does not open. */
static long decrypt(const u8 ua_priv[32], const u8 ua_pub[65], const u8 auth[16], const u8 *body, size_t n, u8 *pt) {
    u8 as_pub[65], shared[65], key[32], ikm[32], prk[32], cek[32], nonce[32], info[160];
    br_aes_ct_ctr_keys ac;
    br_gcm_context g;
    size_t ctn, o = 0;
    if (n < 86 + 17 || memcmp(body + 16, "\x00\x00\x10\x00\x41", 5) != 0) {
        return -1;
    }
    memcpy(as_pub, body + 21, 65);
    memcpy(shared, as_pub, 65);
    if (!br_ec_p256_m31.mul(shared, 65, ua_priv, 32, BR_EC_secp256r1)) {
        return -1;
    }
    hmac(key, auth, 16, shared + 1, 32, NULL, 0);
    memcpy(info, "WebPush: info", 14);
    o = 14;
    memcpy(info + o, ua_pub, 65);
    o += 65;
    memcpy(info + o, as_pub, 65);
    o += 65;
    info[o++] = 1;
    hmac(ikm, key, 32, info, o, NULL, 0);
    hmac(prk, body, 16, ikm, 32, NULL, 0);
    hmac(cek, prk, 32, "Content-Encoding: aes128gcm\0\1", 29, NULL, 0);
    hmac(nonce, prk, 32, "Content-Encoding: nonce\0\1", 25, NULL, 0);
    ctn = n - 86 - 16;
    memcpy(pt, body + 86, ctn);
    br_aes_ct_ctr_init(&ac, cek, 16);
    br_gcm_init(&g, &ac.vtable, br_ghash_ctmul32);
    br_gcm_reset(&g, nonce, 12);
    br_gcm_flip(&g);
    br_gcm_run(&g, 0, pt, ctn);
    if (!br_gcm_check_tag(&g, body + 86 + ctn) || ctn == 0 || pt[ctn - 1] != 0x02) {
        return -1;
    }
    return (long)ctn - 1;
}

/* Checks request K as the push service would; returns the salt for a freshness check. */
static void check_request(int k, int port, const u8 vapid_pub[65], const u8 ua_priv[32], const u8 ua_pub[65],
                          const u8 auth[16], const char *topic, const char *payload, u8 salt[16]) {
    char path[1200], v[1024], want[256], *req, *head_end;
    const char *body_start;
    size_t len;
    u8 pt[4200];
    long ptn;
    (void)snprintf(path, sizeof path, "%s/%d.req", logdir, k);
    req = slurp(path, &len);
    head_end = strstr(req, "\r\n\r\n");
    assert(head_end);
    body_start = head_end + 4;
    assert(strncmp(req, "POST /wpush/v2/abc HTTP/1.1\r\n", 29) == 0);
    assert(header(req, "TTL", v, sizeof v) && strcmp(v, "3600") == 0);
    assert(header(req, "Urgency", v, sizeof v) && strcmp(v, "normal") == 0);
    if (topic) {
        assert(header(req, "Topic", v, sizeof v) && strcmp(v, topic) == 0);
    } else {
        assert(!header(req, "Topic", v, sizeof v));
    }
    assert(header(req, "Content-Encoding", v, sizeof v) && strcmp(v, "aes128gcm") == 0);
    assert(header(req, "Content-Type", v, sizeof v) && strcmp(v, "application/octet-stream") == 0);
    assert(!strstr(req, "application/json"));
    (void)snprintf(want, sizeof want, "%zu", strlen(payload) + PIC_WEBPUSH_OVERHEAD);
    assert(header(req, "Content-Length", v, sizeof v) && strcmp(v, want) == 0);
    assert((size_t)(req + len - body_start) == strlen(payload) + PIC_WEBPUSH_OVERHEAD);
    /* The token: vapid t=HEADER.CLAIMS.SIG, k=PUB; the signature verifies under k. */
    assert(header(req, "Authorization", v, sizeof v) && strncmp(v, "vapid t=", 8) == 0);
    {
        char *t = v + 8, *comma = strstr(t, ", k="), *d1 = strchr(t, '.'), *d2 = d1 ? strchr(d1 + 1, '.') : NULL;
        u8 claims[512], sig[64], hash[32], kpub[65];
        size_t cn;
        char kb[96], expect[256];
        long long exp;
        br_sha256_context sc;
        br_ec_public_key pk = {BR_EC_secp256r1, kpub, 65};
        assert(comma && d1 && d2 && d2 < comma);
        b64(vapid_pub, 65, kb);
        assert(strcmp(comma + 4, kb) == 0);
        assert(unb64(comma + 4, strlen(comma + 4), kpub) == 65);
        assert(strncmp(t, "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.", 37) == 0);
        cn = unb64(d1 + 1, (size_t)(d2 - d1 - 1), claims);
        claims[cn] = '\0';
        (void)snprintf(expect, sizeof expect, "{\"aud\":\"http://127.0.0.1:%d\",\"exp\":", port);
        assert(strncmp((char *)claims, expect, strlen(expect)) == 0);
        exp = strtoll((char *)claims + strlen(expect), NULL, 10);
        assert(exp >= (long long)time(NULL) + PIC_WEBPUSH_EXPIRY - 120 && exp <= (long long)time(NULL) + PIC_WEBPUSH_EXPIRY + 5);
        assert(strstr((char *)claims, ",\"sub\":\"https://relay.example\"}"));
        assert(unb64(d2 + 1, (size_t)(comma - d2 - 1), sig) == 64);
        br_sha256_init(&sc);
        br_sha256_update(&sc, t, (size_t)(d2 - t));
        br_sha256_out(&sc, hash);
        assert(br_ecdsa_i31_vrfy_raw(&br_ec_p256_m31, hash, 32, &pk, sig, 64) == 1);
    }
    ptn = decrypt(ua_priv, ua_pub, auth, (const u8 *)body_start, strlen(payload) + PIC_WEBPUSH_OVERHEAD, pt);
    assert(ptn == (long)strlen(payload) && memcmp(pt, payload, (size_t)ptn) == 0);
    memcpy(salt, body_start, 16);
    free(req);
}

static void test_send(const char *bin, const char *work) {
    char *specs[] = {"status:201:-", "status:404:-", "status:410:-", "status:413:-", "retry:429:30",
                     "head:429:-:retry-after: Wed, 21 Oct 2026 07:28:00 GMT", "status:400:-", "status:500:-"};
    static const struct {
        pic_webpush_outcome outcome;
        int status;
        long retry;
    } want[] = {{PIC_WEBPUSH_SENT, 201, -1},    {PIC_WEBPUSH_GONE, 404, -1},  {PIC_WEBPUSH_GONE, 410, -1},
                {PIC_WEBPUSH_TOO_LARGE, 413, -1}, {PIC_WEBPUSH_RETRY, 429, 30}, {PIC_WEBPUSH_RETRY, 429, -1},
                {PIC_WEBPUSH_FAILED, 400, -1},  {PIC_WEBPUSH_FAILED, 500, -1}};
    const int n = (int)(sizeof want / sizeof want[0]);
    u8 ua_priv[32], ua_pub[65], vapid_pub[65], salts[8][16];
    char endpoint[128], topic[PIC_WEBPUSH_TOPIC], err[160];
    pic_webpush_sub sub;
    pic_webpush_vapid vapid;
    pic_webpush_result res;
    pic_net *net;
    int port;
    assert(sizeof specs / sizeof specs[0] == (size_t)n);
    fill(ua_priv, 0x71);
    pubkey(ua_priv, ua_pub);
    memcpy(sub.p256dh, ua_pub, 65);
    assert(unhex("000102030405060708090a0b0c0d0e0f", sub.auth) == 16);
    fill(vapid.priv, 0x51);
    vapid.subject = "https://relay.example";
    pubkey(vapid.priv, vapid_pub);
    pic_webpush_topic(sub.auth, "w1/c1", topic);
    port = start_server(bin, work, specs, n);
    (void)snprintf(endpoint, sizeof endpoint, "http://127.0.0.1:%d/wpush/v2/abc", port);
    sub.endpoint = endpoint;
    net = pic_net_new(err, sizeof err);
    assert(net);
    for (int i = 0; i < n; i++) {
        int rc = pic_webpush_send(net, &sub, &vapid, i == 1 ? NULL : topic, PUSH_PT, strlen(PUSH_PT), 3600, &res);
        if (res.outcome != want[i].outcome || res.status != want[i].status || res.retry_after != want[i].retry) {
            fprintf(stderr, "send %d: outcome %d status %d retry %ld err %s\n", i, res.outcome, res.status,
                    res.retry_after, res.err);
            assert(0);
        }
        assert(rc == (want[i].outcome == PIC_WEBPUSH_SENT ? 0 : -1));
        assert(want[i].outcome == PIC_WEBPUSH_SENT || res.err[0] != '\0');
        check_request(i + 1, port, vapid_pub, ua_priv, ua_pub, sub.auth, i == 1 ? NULL : topic, PUSH_PT, salts[i]);
    }
    /* Every push has its own salt (and so its own key pair, which the decrypt above took). */
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            assert(memcmp(salts[i], salts[j], 16) != 0);
        }
    }
    /* Too large a payload is refused before anything is sent. */
    {
        char *big = calloc(1, PIC_WEBPUSH_MAX + 2);
        char path[1200];
        assert(big);
        memset(big, 'a', PIC_WEBPUSH_MAX + 1);
        assert(pic_webpush_send(net, &sub, &vapid, topic, big, PIC_WEBPUSH_MAX + 1, 3600, &res) == -1);
        assert(res.outcome == PIC_WEBPUSH_TOO_LARGE && res.status == 0);
        (void)snprintf(path, sizeof path, "%s/%d.req", logdir, n + 1);
        assert(access(path, F_OK) != 0);
        free(big);
    }
    /* A topic that is not base64url, or too long, is refused before anything is sent. */
    assert(pic_webpush_send(net, &sub, &vapid, "a b", PUSH_PT, strlen(PUSH_PT), 3600, &res) == -1);
    assert(res.outcome == PIC_WEBPUSH_FAILED && res.status == 0);
    assert(pic_webpush_send(net, &sub, &vapid, "abcdefghijklmnopqrstuvwxyz0123456", PUSH_PT, strlen(PUSH_PT), 3600,
                            &res) == -1);
    assert(res.outcome == PIC_WEBPUSH_FAILED && res.status == 0);
    /* A subscription key off the curve, or not uncompressed, is refused before anything is sent. */
    sub.p256dh[64] ^= 1;
    assert(pic_webpush_send(net, &sub, &vapid, topic, PUSH_PT, strlen(PUSH_PT), 3600, &res) == -1);
    assert(res.outcome == PIC_WEBPUSH_FAILED && res.status == 0);
    sub.p256dh[64] ^= 1;
    sub.p256dh[0] = 0x02;
    assert(pic_webpush_send(net, &sub, &vapid, topic, PUSH_PT, strlen(PUSH_PT), 3600, &res) == -1);
    assert(res.outcome == PIC_WEBPUSH_FAILED && res.status == 0);
    sub.p256dh[0] = 0x04;
    {
        char path[1200];
        (void)snprintf(path, sizeof path, "%s/%d.req", logdir, n + 1);
        assert(access(path, F_OK) != 0);
    }
    stop_server();
    /* No service listening: failed, with no status. */
    assert(pic_webpush_send(net, &sub, &vapid, topic, PUSH_PT, strlen(PUSH_PT), 3600, &res) == -1);
    assert(res.outcome == PIC_WEBPUSH_FAILED && res.status == 0 && res.err[0] != '\0');
    pic_net_free(net);
}

int main(int argc, char **argv) {
    char cmd[2100];
    assert(argc == 3);
    test_vapid();
    test_topic();
    test_endpoint();
    (void)snprintf(cmd, sizeof cmd, "rm -rf '%s' && mkdir -p '%s/log'", argv[2], argv[2]);
    assert(system(cmd) == 0);
    test_send(argv[1], argv[2]);
    puts("webpush: ok");
    return 0;
}