summaryrefslogtreecommitdiff
path: root/openwrt/uci.nix
blob: d6d328866f91053b702b6762575645fa303dbf69 (plain)
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
{ pkgs, lib, config, ... }:

let
  cfg = config.uci;

  formatConfig = nix:
    lib.concatStringsSep
      "\n"
      (lib.flatten
        (lib.mapAttrsToList
          (config: sections: [
            "package ${config}"
            (lib.mapAttrsToList formatSections sections)
          ])
          nix));

  formatSections = type: sections:
    if lib.isAttrs sections
    then
      lib.mapAttrsToList
        (name: vals: [
          "config ${type} ${formatScalar name}"
          (formatSection vals)
        ])
        sections
    else
      map
        (vals: [
          "config ${type}"
          (formatSection vals)
        ])
        sections;

  formatSection =
    lib.mapAttrsToList
      (option: value:
        if lib.isList value
        then map (value: "  list ${option} ${formatScalar value}") value
        else "  option ${option} ${formatScalar value}");

  formatScalar = val:
    if lib.isBool val then (if val then "'1'" else "'0'")
    else if lib.isInt val then "'${toString val}'"
    else if lib.isAttrs val then "'${secretName val._secret}'"
    else "'${lib.replaceStrings [ "'" ] [ "'\\''" ] val}'";

  secretName = sec: "@secret_${sec}_${builtins.hashString "sha256" sec}@";

  collectSecrets = nix:
    lib.pipe nix [
      lib.attrValues
      (lib.concatMap lib.attrValues)
      (lib.concatMap (s: if lib.isAttrs s then lib.attrValues s else s))
      (lib.concatMap lib.attrValues)
      (lib.concatMap lib.toList)
      (lib.concatMap (v: if v ? _secret then [{ name = v._secret; value = {}; }] else []))
      lib.listToAttrs
      lib.attrNames
    ];

  uciIdentifierCheck = type: attrs:
    let
      invalid = lib.filter
        (n: builtins.match "[a-zA-Z0-9_]+" n == null)
        (lib.attrNames attrs);
    in
      lib.warnIf
        (invalid != [])
        ("Invalid UCI ${type} names found: ${toString invalid}")
        (invalid == []);
in

{
  options.uci = {
    secretsCommand = lib.mkOption {
      type = lib.types.path;
      default = pkgs.writeScript "no-secrets" "echo '{}'";
      description = ''
        Command to retrieve secrets. Must be an executable command that
        returns a JSON object on `stdout`, with secret names as keys and string
        values.
      '';
    };

    sopsSecrets = lib.mkOption {
      type = lib.types.nullOr lib.types.path;
      default = null;
      description = ''
        sops secrets file. This as a shorthand for setting {option}`secretsCommand`
        to a script that calls `sops -d <path>`. Path semantics apply: if the given
        path is a path literal it is copied into the store and the resulting absolute
        path is used, otherwise the given path is used verbatim in the generated script.
      '';
    };

    settings = lib.mkOption {
      type = with lib.types;
        let
          scalar = oneOf [
            str
            int
            bool
            (submodule {
              options._secret = lib.mkOption {
                type = str;
                description = ''
                  Name of the secret to insert into the config from data exported
                  by {option}`secretsCommand`. Secrets are always interpolated as
                  strings, which uci allows for scalars. Lists cannot currently
                  be made entirely secret, only individual values of lists can.
                '';
              };
            })
          ];
          uciAttrsOf = type: elem: addCheck (attrsOf elem) (uciIdentifierCheck type);
          options = uciAttrsOf "option" (either scalar (listOf scalar));
        in
          submodule {
            freeformType =
              # <config>.<name>=type       -> config.type.name ...
              # <config>.@<anonymous>=type -> config.type = [{ ... }]
              attrsOf # config
                (attrsOf # type
                  (either
                    (uciAttrsOf "section" options) # name ...
                    (listOf options) # [{ ... }]
                  ))
              // {
                description = "UCI config";
              };
          };
      default = {};
      description = ''
        UCI settings in hierarchical representation. The toplevel key of this
        set denotes a UCI package, the second level the type of section, and the
        third level may be either a list of anonymous setions or a set of named
        sections.

        Packages defined here will replace existing settings on the system entirely,
        no merging with existing configuration is done.
      '';
      example = {
        network = {
          interface.loopback = {
            device = "lo";
            proto = "static";
            ipaddr = "127.0.0.1";
            netmask = "255.0.0.0";
          };

          globals = [{ ula_prefix = "fdb8:155d:7ef5::/48"; }];
        };
      };
    };

    retain = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [];
      example = [ "ucitrack" ];
      description = ''
        UCI package configuration to retain. Packages listed here will not have preexisting
        configuration deleted during deployment, even if no matching {option}`settings`
        are defined.
      '';
    };
  };

  config = {
    uci.secretsCommand = lib.mkIf (cfg.sopsSecrets != null)
      (pkgs.writeShellScript "sops" ''
        ${pkgs.sops}/bin/sops --output-type json -d ${lib.escapeShellArg "${cfg.sopsSecrets}"}
      '');

    build.configFile = pkgs.writeText "config" (formatConfig cfg.settings);

    deploySteps.uciConfig =
      # correctness of config identifiers can't be checked on the type level
      # because submodules are weird sometimes, so we have to do it here.
      assert uciIdentifierCheck "config" cfg.settings;
      let
        cfgName = baseNameOf config.build.configFile;
        jq = "${pkgs.jq}/bin/jq";
        configured = lib.attrNames config.uci.settings ++ config.uci.retain;
      in
        {
          priority = 4999;
          prepare = ''
            cp --no-preserve=all ${config.build.configFile} "$TMP"
            (
              umask 0077
              C="$TMP"/${cfgName}
              S="$TMP"/secrets
              ${cfg.secretsCommand} > "$S"
              [ "$(${jq} -r type <"$S")" == "object" ] || {
                log_err "secrets command did not produce an object"
                exit 1
              }
              ${lib.concatMapStrings
                (secret: let arg = lib.escapeShellArg secret; in ''
                  has="$(${jq} -r --arg s ${arg} 'has($s)' <"$S")"
                  $has || {
                    log_err secret ${arg} not defined
                    exit 1
                  }
                  ${pkgs.replace-secret}/bin/replace-secret \
                    ${lib.escapeShellArg (secretName secret)} \
                    <(${jq} -r --arg s ${arg} '.[$s]'" | tostring | sub(\"'\"; \"'\\\\'''\")" <"$S") \
                    "$C"
                '')
                (collectSecrets cfg.settings)}
            )
          '';
          copy = ''
            scp "$TMP"/${cfgName} device:/tmp/
          '';
          apply = ''
            uci import < /tmp/${cfgName}
            uci commit

            (
              cd /etc/config
              for cfg in *; do
                case "$cfg" in
                  ${lib.optionalString (configured != []) ''
                    ${lib.concatMapStringsSep "|" lib.escapeShellArg configured}) : ;;
                  ''}
                  *) rm "$cfg" ;;
                esac
              done
            )
          '';
        };
  };
}