Skip to content
Snippets Groups Projects
issuer.nix 8.46 KiB
# A NixOS module which can run a Ristretto-based issuer for PrivateStorage
# ZKAPs.
{ lib, pkgs, ourpkgs, config, ... }: let
  cfg = config.services.private-storage-issuer;
in {
  options = {
    services.private-storage-issuer.enable = lib.mkEnableOption "PrivateStorage ZKAP Issuer Service";
    services.private-storage-issuer.package = lib.mkOption {
      default = ourpkgs.zkapissuer;
      type = lib.types.package;
      example = "pkgs.zkapissuer.components.exes.\"PaymentServer-exe\"";
      description = ''
        The package to use for the ZKAP issuer.
      '';
    };
    services.private-storage-issuer.domains = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      example = [ "payments.example.com" ];
      description = ''
        The domain names at which the issuer is reachable.
      '';
    };
    services.private-storage-issuer.tls = lib.mkOption {
      default = true;
      type = lib.types.bool;
      description = ''
        Whether or not to listen on TLS.  For real-world use you should always
        listen on TLS.  This is provided as an aid to automated testing where
        it might be difficult to obtain a real certificate.
      '';
    };
    services.private-storage-issuer.issuer = lib.mkOption {
      default = "Ristretto";
      type = lib.types.enum [ "Trivial" "Ristretto" ];
      example = "Trivial";
      description = ''
        The issuer algorithm to use.  Either Trivial for a fake no-crypto
        algorithm or Ristretto for Ristretto-flavored PrivacyPass.
      '';
    };
    services.private-storage-issuer.ristrettoSigningKeyPath = lib.mkOption {
      default = null;
      type = lib.types.path;
      description = ''
        The path to a file containing the Ristretto signing key to use.
        Required if the issuer is ``Ristretto``.
      '';
    };
    services.private-storage-issuer.stripeSecretKeyPath = lib.mkOption {
      type = lib.types.path;
      description = ''
        The path to a file containing a Stripe secret key to use for charge
        and payment management.
      '';
    };
    services.private-storage-issuer.stripeEndpointDomain = lib.mkOption {
      type = lib.types.str;
      description = ''
        The domain name for the Stripe API HTTP endpoint.
      '';
      default = "api.stripe.com";
    };
    services.private-storage-issuer.stripeEndpointScheme = lib.mkOption {
      type = lib.types.enum [ "HTTP" "HTTPS" ];
      description = ''
        Whether to use HTTP or HTTPS for the Stripe API.
      '';
      default = "HTTPS";
    };
    services.private-storage-issuer.stripeEndpointPort = lib.mkOption {
      type = lib.types.int;
      description = ''
        The port number for the Stripe API HTTP endpoint.
      '';
      default = 443;
    };
    services.private-storage-issuer.database = lib.mkOption {
      default = "Memory";
      type = lib.types.enum [ "Memory" "SQLite3" ];
      description = ''
        The kind of voucher database to use.
      '';
    };
    services.private-storage-issuer.databasePath = lib.mkOption {
      default = null;
      type = lib.types.str;
      description = ''
        The path to a database file in the filesystem, if the SQLite3 database
        type is being used.
      '';
    };
    services.private-storage-issuer.letsEncryptAdminEmail = lib.mkOption {
      type = lib.types.str;
      description = ''
        An email address to give to Let's Encrypt as an operational contact
        for the service's TLS certificate.
      '';
    };
    services.private-storage-issuer.allowedChargeOrigins = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      description = ''
        The CORS "Origin" values which are allowed to submit charges to the
        payment server.  Note this is not currently enforced by the
        PaymentServer.  It just controls the CORS headers served.
      '';
    };
  };

  config =
    let
      # We'll refer to this collection of domains by the first domain in the
      # list.
      domain = builtins.head cfg.domains;
      certServiceName = "acme-${domain}";
      # Payment server internal http port (arbitrary, non-priviledged):
      internalHttpPort = "1061";

    in lib.mkIf cfg.enable {
    # Add a systemd service to run PaymentServer.
    systemd.services.zkapissuer = {
      enable = true;
      description = "ZKAP Issuer";
      wantedBy = [ "multi-user.target" ];

      # It really shouldn't ever exit on its own!  If it does, it's a bug
      # we'll have to fix.  Restart it and hope it doesn't happen too much
      # before we can fix whatever the issue is.
      serviceConfig.Restart = "always";
      serviceConfig.Type = "simple";

      # Run w/o privileges
      serviceConfig = {
        DynamicUser = false;
        User = "zkapissuer";
        Group = "zkapissuer";
      };

      # Make systemd create a User/Group owned directory for PaymentServer
      # state. According to the docs at
      # https://www.freedesktop.org/software/systemd/man/systemd.exec.html#RuntimeDirectory=
      # "The specified directory names must be relative" ... this
      # makes systemd create /var/lib/zkapissuer/ for us:
      serviceConfig.StateDirectory = "zkapissuer";
      serviceConfig.StateDirectoryMode = "0750";

      # Bail if there is still an old (root-owned) DB file on this system.
      # If you hit this, and this /var/db/ file is indeed current, move it to
      # /var/lib/zkapissuer/vouchers.sqlite3 and chown it to zkapissuer:zkapissuer.
      unitConfig.AssertPathExists = "!/var/db/vouchers.sqlite3";

      script =
        let
          # Compute the right command line arguments to pass to it.  The
          # signing key is only supplied when using the Ristretto issuer.
          issuerArgs =
            if cfg.issuer == "Trivial"
              then "--issuer Trivial"
              else "--issuer Ristretto --signing-key-path ${cfg.ristrettoSigningKeyPath}";
          databaseArgs =
            if cfg.database == "Memory"
              then "--database Memory"
              else "--database SQLite3 --database-path ${cfg.databasePath}";
          httpArgs = "--http-port ${internalHttpPort}";

          prefixOption = s: "--cors-origin=" + s;
          originStrings = map prefixOption cfg.allowedChargeOrigins;
          originArgs = builtins.concatStringsSep " " originStrings;

          stripeArgs =
            "--stripe-key-path ${cfg.stripeSecretKeyPath} " +
            "--stripe-endpoint-domain ${cfg.stripeEndpointDomain} " +
            "--stripe-endpoint-scheme ${cfg.stripeEndpointScheme} " +
            "--stripe-endpoint-port ${toString cfg.stripeEndpointPort}";
        in
          "${cfg.package.exePath} ${originArgs} ${issuerArgs} ${databaseArgs} ${httpArgs} ${stripeArgs}";
    };

    # PaymentServer runs as this user and group by default
    # Mind the comments in nixpkgs/nixos/modules/misc/ids.nix: "When adding a uid,
    # make sure it doesn't match an existing gid. And don't use uids above 399!"
    ids.uids.zkapissuer = 397;
    ids.gids.zkapissuer = 397;
    users.extraGroups.zkapissuer.gid = config.ids.gids.zkapissuer;
    users.extraUsers.zkapissuer = {
      uid = config.ids.uids.zkapissuer;
      isNormalUser = false;
      group = "zkapissuer";
      # Let PaymentServer read from keys, if necessary.
      extraGroups = [ "keys" ];
    };

    # Open 80 and 443 for nginx
    networking.firewall.allowedTCPPorts = [
      80
      443
    ];

    # NGINX reverse proxy
    security.acme.email = cfg.letsEncryptAdminEmail;
    security.acme.acceptTerms = true;
    services.nginx = {
      enable = true;

      recommendedGzipSettings = true;
      recommendedOptimisation = true;
      recommendedProxySettings = true;
      recommendedTlsSettings = true;

      virtualHosts."${domain}" = {
        serverAliases = builtins.tail cfg.domains;
        enableACME = cfg.tls;
        forceSSL = cfg.tls;
        locations."/v1/" = {
          # Only forward requests beginning with /v1/ so
          # we pass less scanning spam on to our backend
          # Want a regex instead? try locations."~ /v\d+/"
          proxyPass = "http://127.0.0.1:${internalHttpPort}";
        };
        locations."/metrics" = {
          # Only allow our monitoringvpn subnet
          extraConfig = ''
            allow 172.23.23.0/24;
            deny all;
          '';
          proxyPass = "http://127.0.0.1:${internalHttpPort}";
        };
        locations."/" = {
          # Return a 404 error for any paths not specified above.
          extraConfig = ''
            return 404;
          '';
        };
      };
    };

  };
}