1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This is the auth-source.el package. It lets users tell Gnus how to
26 ;; authenticate in a single place. Simplicity is the goal. Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (defvar secrets-enabled)
69 (defgroup auth-source nil
70 "Authentication sources."
71 :version "23.1" ;; No Gnus
75 (defcustom auth-source-cache-expiry 7200
76 "How many seconds passwords are cached, or nil to disable
77 expiring. Overrides `password-cache-expiry' through a
80 :type '(choice (const :tag "Never" nil)
81 (const :tag "All Day" 86400)
82 (const :tag "2 Hours" 7200)
83 (const :tag "30 Minutes" 1800)
84 (integer :tag "Seconds")))
86 (defclass auth-source-backend ()
91 :documentation "The backend type.")
92 (source :initarg :source
95 :documentation "The backend source.")
100 :documentation "The backend host.")
105 :documentation "The backend user.")
110 :documentation "The backend protocol.")
111 (create-function :initarg :create-function
115 :documentation "The create function.")
116 (search-function :initarg :search-function
120 :documentation "The search function.")))
122 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
123 (pop3 "pop3" "pop" "pop3s" "110" "995")
127 "List of authentication protocols and their names"
130 :version "23.2" ;; No Gnus
131 :type '(repeat :tag "Authentication Protocols"
132 (cons :tag "Protocol Entry"
133 (symbol :tag "Protocol")
135 (string :tag "Name")))))
137 ;;; generate all the protocols in a format Customize can use
138 ;;; TODO: generate on the fly from auth-source-protocols
139 (defconst auth-source-protocols-customize
141 (let ((p (car-safe a)))
143 :tag (upcase (symbol-name p))
145 auth-source-protocols))
147 (defvar auth-source-creation-defaults nil
148 "Defaults for creating token values. Usually let-bound.")
150 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
152 (defvar auth-source-magic "auth-source-magic ")
154 (defcustom auth-source-do-cache t
155 "Whether auth-source should cache information with `password-cache'."
157 :version "23.2" ;; No Gnus
160 (defcustom auth-source-debug nil
161 "Whether auth-source should log debug messages.
163 If the value is nil, debug messages are not logged.
165 If the value is t, debug messages are logged with `message'. In
166 that case, your authentication data will be in the clear (except
169 If the value is a function, debug messages are logged by calling
170 that function using the same arguments as `message'."
172 :version "23.2" ;; No Gnus
174 :tag "auth-source debugging mode"
175 (const :tag "Log using `message' to the *Messages* buffer" t)
176 (const :tag "Log all trivia with `message' to the *Messages* buffer"
178 (function :tag "Function that takes arguments like `message'")
179 (const :tag "Don't log anything" nil)))
181 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
182 "List of authentication sources.
184 The default will get login and password information from
185 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
186 packages to be encrypted. If that file doesn't exist, it will
187 try the unencrypted version \"~/.authinfo\" and the famous
190 See the auth.info manual for details.
192 Each entry is the authentication type with optional properties.
194 It's best to customize this with `M-x customize-variable' because the choices
195 can get pretty complex."
197 :version "24.1" ;; No Gnus
198 :type `(repeat :tag "Authentication Sources"
200 (string :tag "Just a file")
201 (const :tag "Default Secrets API Collection" 'default)
202 (const :tag "Login Secrets API Collection" "secrets:Login")
203 (const :tag "Temp Secrets API Collection" "secrets:session")
204 (list :tag "Source definition"
205 (const :format "" :value :source)
206 (choice :tag "Authentication backend choice"
207 (string :tag "Authentication Source (file)")
209 :tag "Secret Service API/KWallet/GNOME Keyring"
210 (const :format "" :value :secrets)
211 (choice :tag "Collection to use"
212 (string :tag "Collection name")
213 (const :tag "Default" 'default)
214 (const :tag "Login" "Login")
216 :tag "Temporary" "session"))))
217 (repeat :tag "Extra Parameters" :inline t
218 (choice :tag "Extra parameter"
221 (const :format "" :value :host)
222 (choice :tag "Host (machine) choice"
225 :tag "Regular expression")))
228 (const :format "" :value :port)
232 ,@auth-source-protocols-customize))
233 (list :tag "User" :inline t
234 (const :format "" :value :user)
235 (choice :tag "Personality/Username"
237 (string :tag "Name")))))))))
239 (defcustom auth-source-gpg-encrypt-to t
240 "List of recipient keys that `authinfo.gpg' encrypted to.
241 If the value is not a list, symmetric encryption will be used."
243 :version "24.1" ;; No Gnus
244 :type '(choice (const :tag "Symmetric encryption" t)
245 (repeat :tag "Recipient public keys"
246 (string :tag "Recipient public key"))))
248 ;; temp for debugging
249 ;; (unintern 'auth-source-protocols)
250 ;; (unintern 'auth-sources)
251 ;; (customize-variable 'auth-sources)
252 ;; (setq auth-sources nil)
253 ;; (format "%S" auth-sources)
254 ;; (customize-variable 'auth-source-protocols)
255 ;; (setq auth-source-protocols nil)
256 ;; (format "%S" auth-source-protocols)
257 ;; (auth-source-pick nil :host "a" :port 'imap)
258 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
259 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
260 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
261 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
262 ;; (auth-source-protocol-defaults 'imap)
264 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
265 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
266 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
267 (defun auth-source-do-debug (&rest msg)
268 (when auth-source-debug
269 (apply 'auth-source-do-warn msg)))
271 (defun auth-source-do-trivia (&rest msg)
272 (when (or (eq auth-source-debug 'trivia)
273 (functionp auth-source-debug))
274 (apply 'auth-source-do-warn msg)))
276 (defun auth-source-do-warn (&rest msg)
278 ;; set logger to either the function in auth-source-debug or 'message
279 ;; note that it will be 'message if auth-source-debug is nil
280 (if (functionp auth-source-debug)
286 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
287 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
288 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
289 ;; (:source (:secrets "session") :host t :port t :user "joe")
290 ;; (:source (:secrets "Login") :host t :port t)
291 ;; (:source "~/.authinfo.gpg" :host t :port t)))
293 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
294 ;; (:source (:secrets "session") :host t :port t :user "joe")
295 ;; (:source (:secrets "Login") :host t :port t)
298 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
300 ;; (auth-source-backend-parse "myfile.gpg")
301 ;; (auth-source-backend-parse 'default)
302 ;; (auth-source-backend-parse "secrets:Login")
304 (defun auth-source-backend-parse (entry)
305 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
306 (auth-source-backend-parse-parameters
309 ;; take 'default and recurse to get it as a Secrets API default collection
310 ;; matching any user, host, and protocol
312 (auth-source-backend-parse '(:source (:secrets default))))
313 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
314 ;; matching any user, host, and protocol
315 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
316 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
317 ;; take just a file name and recurse to get it as a netrc file
318 ;; matching any user, host, and protocol
320 (auth-source-backend-parse `(:source ,entry)))
322 ;; a file name with parameters
323 ((stringp (plist-get entry :source))
325 (plist-get entry :source)
326 :source (plist-get entry :source)
328 :search-function 'auth-source-netrc-search
329 :create-function 'auth-source-netrc-create))
331 ;; the Secrets API. We require the package, in order to have a
332 ;; defined value for `secrets-enabled'.
334 (not (null (plist-get entry :source))) ; the source must not be nil
335 (listp (plist-get entry :source)) ; and it must be a list
336 (require 'secrets nil t) ; and we must load the Secrets API
337 secrets-enabled) ; and that API must be enabled
339 ;; the source is either the :secrets key in ENTRY or
340 ;; if that's missing or nil, it's "session"
341 (let ((source (or (plist-get (plist-get entry :source) :secrets)
344 ;; if the source is a symbol, we look for the alias named so,
345 ;; and if that alias is missing, we use "Login"
346 (when (symbolp source)
347 (setq source (or (secrets-get-alias (symbol-name source))
350 (if (featurep 'secrets)
352 (format "Secrets API (%s)" source)
355 :search-function 'auth-source-secrets-search
356 :create-function 'auth-source-secrets-create)
358 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
360 (format "Ignored Secrets API (%s)" source)
367 "auth-source-backend-parse: invalid backend spec: %S" entry)
373 (defun auth-source-backend-parse-parameters (entry backend)
374 "Fills in the extra auth-source-backend parameters of ENTRY.
375 Using the plist ENTRY, get the :host, :port, and :user search
377 (let ((entry (if (stringp entry)
381 (when (setq val (plist-get entry :host))
382 (oset backend host val))
383 (when (setq val (plist-get entry :user))
384 (oset backend user val))
385 (when (setq val (plist-get entry :port))
386 (oset backend port val)))
389 ;; (mapcar 'auth-source-backend-parse auth-sources)
391 (defun* auth-source-search (&rest spec
392 &key type max host user port secret
395 "Search or modify authentication backends according to SPEC.
397 This function parses `auth-sources' for matches of the SPEC
398 plist. It can optionally create or update an authentication
399 token if requested. A token is just a standard Emacs property
400 list with a :secret property that can be a function; all the
401 other properties will always hold scalar values.
403 Typically the :secret property, if present, contains a password.
405 Common search keys are :max, :host, :port, and :user. In
406 addition, :create specifies how tokens will be or created.
407 Finally, :type can specify which backend types you want to check.
409 A string value is always matched literally. A symbol is matched
410 as its string value, literally. All the SPEC values can be
411 single values (symbol or string) or lists thereof (in which case
412 any of the search terms matches).
414 :create t means to create a token if possible.
416 A new token will be created if no matching tokens were found.
417 The new token will have only the keys the backend requires. For
418 the netrc backend, for instance, that's the user, host, and
423 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
424 (A . \"default A\"))))
425 (auth-source-search :host \"mine\" :type 'netrc :max 1
426 :P \"pppp\" :Q \"qqqq\"
431 \"Search for any entry matching host 'mine' in backends of type
432 'netrc', maximum one result.
434 Create a new entry if you found none. The netrc backend will
435 automatically require host, user, and port. The host will be
436 'mine'. We prompt for the user with default 'defaultUser' and
437 for the port without a default. We will not prompt for A, Q,
438 or P. The resulting token will only have keys user, host, and
441 :create '(A B C) also means to create a token if possible.
443 The behavior is like :create t but if the list contains any
444 parameter, that parameter will be required in the resulting
445 token. The value for that parameter will be obtained from the
446 search parameters or from user input. If any queries are needed,
447 the alist `auth-source-creation-defaults' will be checked for the
452 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
453 (A . \"default A\"))))
454 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
455 :P \"pppp\" :Q \"qqqq\"
460 \"Search for any entry matching host 'nonesuch'
461 or 'twosuch' in backends of type 'netrc', maximum one result.
463 Create a new entry if you found none. The netrc backend will
464 automatically require host, user, and port. The host will be
465 'nonesuch' and Q will be 'qqqq'. We prompt for A with default
466 'default A', for B and port with default nil, and for the
467 user with default 'defaultUser'. We will not prompt for Q. The
468 resulting token will have keys user, host, port, A, B, and Q.
469 It will not have P with any value, even though P is used in the
470 search to find only entries that have P set to 'pppp'.\"
472 When multiple values are specified in the search parameter, the
473 user is prompted for which one. So :host (X Y Z) would ask the
474 user to choose between X, Y, and Z.
476 This creation can fail if the search was not specific enough to
477 create a new token (it's up to the backend to decide that). You
478 should `catch' the backend-specific error as usual. Some
479 backends (netrc, at least) will prompt the user rather than throw
482 :delete t means to delete any found entries. nil by default.
483 Use `auth-source-delete' in ELisp code instead of calling
484 `auth-source-search' directly with this parameter.
486 :type (X Y Z) will check only those backend types. 'netrc and
487 'secrets are the only ones supported right now.
489 :max N means to try to return at most N items (defaults to 1).
490 When 0 the function will return just t or nil to indicate if any
491 matches were found. More than N items may be returned, depending
492 on the search and the backend.
494 :host (X Y Z) means to match only hosts X, Y, or Z according to
495 the match rules above. Defaults to t.
497 :user (X Y Z) means to match only users X, Y, or Z according to
498 the match rules above. Defaults to t.
500 :port (P Q R) means to match only protocols P, Q, or R.
503 :K (V1 V2 V3) for any other key K will match values V1, V2, or
504 V3 (note the match rules above).
506 The return value is a list with at most :max tokens. Each token
507 is a plist with keys :backend :host :port :user, plus any other
508 keys provided by the backend (notably :secret). But note the
509 exception for :max 0, which see above.
511 The token's :secret key can hold a function. In that case you
512 must call it to obtain the actual value."
513 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
515 (ignored-keys '(:create :delete :max))
516 (keys (loop for i below (length spec) by 2
517 unless (memq (nth i spec) ignored-keys)
518 collect (nth i spec)))
519 (found (auth-source-recall spec))
520 filtered-backends accessor-key backend)
522 (if (and found auth-source-do-cache)
523 (auth-source-do-debug
524 "auth-source-search: found %d CACHED results matching %S"
528 (or (eq t create) (listp create)) t
529 "Invalid auth-source :create parameter (must be t or a list): %s %s")
531 (setq filtered-backends (copy-sequence backends))
532 (dolist (backend backends)
534 ;; ignore invalid slots
535 (condition-case signal
536 (unless (eval `(auth-source-search-collection
538 (oref backend ,key)))
539 (setq filtered-backends (delq backend filtered-backends))
541 (invalid-slot-name))))
543 (auth-source-do-trivia
544 "auth-source-search: found %d backends matching %S"
545 (length filtered-backends) spec)
547 ;; (debug spec "filtered" filtered-backends)
548 ;; First go through all the backends without :create, so we can
550 (setq found (auth-source-search-backends filtered-backends
557 (auth-source-do-debug
558 "auth-source-search: found %d results (max %d) matching %S"
559 (length found) max spec)
561 ;; If we didn't find anything, then we allow the backend(s) to
562 ;; create the entries.
565 (setq found (auth-source-search-backends filtered-backends
572 "auth-source-search: CREATED %d results (max %d) matching %S"
573 (length found) max spec))
575 (when (and found auth-source-do-cache)
576 (auth-source-remember spec found)))
580 (defun auth-source-search-backends (backends spec max create delete)
582 (dolist (backend backends)
583 (when (> max (length matches)) ; when we need more matches...
584 (let ((bmatches (apply
585 (slot-value backend 'search-function)
587 ;; note we're overriding whatever the spec
588 ;; has for :create and :delete
593 (auth-source-do-trivia
594 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
595 (length bmatches) max
596 (slot-value backend :type)
597 (slot-value backend :source)
599 (setq matches (append matches bmatches))))))
602 ;;; (auth-source-search :max 1)
603 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
604 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
605 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
607 (defun* auth-source-delete (&rest spec
610 "Delete entries from the authentication backends according to SPEC.
611 Calls `auth-source-search' with the :delete property in SPEC set to t.
612 The backend may not actually delete the entries.
614 Returns the deleted entries."
615 (auth-source-search (plist-put spec :delete t)))
617 (defun auth-source-search-collection (collection value)
618 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
619 (when (and (atom collection) (not (eq t collection)))
620 (setq collection (list collection)))
622 ;; (debug :collection collection :value value)
623 (or (eq collection t)
625 (equal collection value)
626 (member value collection)))
628 (defun auth-source-forget-all-cached ()
629 "Forget all cached auth-source data."
631 (loop for sym being the symbols of password-data
632 ;; when the symbol name starts with auth-source-magic
633 when (string-match (concat "^" auth-source-magic)
636 do (password-cache-remove (symbol-name sym))))
638 (defun auth-source-remember (spec found)
639 "Remember FOUND search results for SPEC."
640 (let ((password-cache-expiry auth-source-cache-expiry))
642 (concat auth-source-magic (format "%S" spec)) found)))
644 (defun auth-source-recall (spec)
645 "Recall FOUND search results for SPEC."
646 (password-read-from-cache
647 (concat auth-source-magic (format "%S" spec))))
649 (defun auth-source-forget (spec)
650 "Forget any cached data matching SPEC exactly.
652 This is the same SPEC you passed to `auth-source-search'.
653 Returns t or nil for forgotten or not found."
654 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
656 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
658 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
659 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
660 ;;; (auth-source-recall '(:host "xedd"))
661 ;;; (auth-source-recall '(:host t))
662 ;;; (auth-source-forget+ :host t)
664 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
665 "Forget any cached data matching SPEC. Returns forgotten count.
667 This is not a full `auth-source-search' spec but works similarly.
668 For instance, \(:host \"myhost\" \"yourhost\") would find all the
669 cached data that was found with a search for those two hosts,
670 while \(:host t) would find all host entries."
673 (loop for sym being the symbols of password-data
674 ;; when the symbol name matches with auth-source-magic
675 when (and (setq sname (symbol-name sym))
676 (string-match (concat "^" auth-source-magic "\\(.+\\)")
678 ;; and the spec matches what was stored in the cache
679 (auth-source-specmatchp spec (read (match-string 1 sname))))
682 (password-cache-remove sname)
686 (defun auth-source-specmatchp (spec stored)
687 (let ((keys (loop for i below (length spec) by 2
688 collect (nth i spec))))
691 (unless (auth-source-search-collection (plist-get stored key)
692 (plist-get spec key))
696 ;;; Backend specific parsing: netrc/authinfo backend
698 (defun auth-source-ensure-strings (values)
699 (unless (listp values)
700 (setq values (list values)))
701 (mapcar (lambda (value)
707 (defvar auth-source-netrc-cache nil)
709 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
710 (defun* auth-source-netrc-parse (&rest
712 &key file max host user port delete
714 "Parse FILE and return a list of all entries in the file.
715 Note that the MAX parameter is used so we can exit the parse early."
717 ;; We got already parsed contents; just return it.
719 (when (file-exists-p file)
720 (setq port (auth-source-ensure-strings port))
722 (let* ((tokens '("machine" "host" "default" "login" "user"
723 "password" "account" "macdef" "force"
725 (max (or max 5000)) ; sanity check: default to stop at 5K
727 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
728 (cached-mtime (plist-get cached :mtime))
729 (cached-secrets (plist-get cached :secret))
730 alist elem result pair)
732 (if (and (functionp cached-secrets)
734 (nth 5 (file-attributes file))))
736 (auth-source-do-trivia
737 "auth-source-netrc-parse: using CACHED file data for %s"
739 (insert (funcall cached-secrets)))
740 (insert-file-contents file)
741 ;; cache all netrc files (used to be just .gpg files)
742 ;; Store the contents of the file heavily encrypted in memory.
743 ;; (note for the irony-impaired: they are just obfuscated)
744 (aput 'auth-source-netrc-cache file
745 (list :mtime (nth 5 (file-attributes file))
746 :secret (lexical-let ((v (rot13-string
747 (base64-encode-string
749 (lambda () (base64-decode-string
750 (rot13-string v)))))))
751 (goto-char (point-min))
752 ;; Go through the file, line by line.
753 (while (and (not (eobp))
756 (narrow-to-region (point) (point-at-eol))
757 ;; For each line, get the tokens and values.
759 (skip-chars-forward "\t ")
760 ;; Skip lines that begin with a "#".
761 (if (eq (char-after) ?#)
762 (goto-char (point-max))
765 (if (= (following-char) ?\")
766 (read (current-buffer))
768 (point) (progn (skip-chars-forward "^\t ")
771 ((equal elem "macdef")
772 ;; We skip past the macro definition.
774 (while (and (zerop (forward-line 1))
776 (narrow-to-region (point) (point)))
777 ((member elem tokens)
778 ;; Tokens that don't have a following value are ignored,
780 (when (and pair (or (cdr pair)
781 (equal (car pair) "default")))
783 (setq pair (list elem)))
785 ;; Values that haven't got a preceding token are ignored.
789 (setq pair nil)))))))
793 (auth-source-search-collection
796 (aget alist "machine")
799 (auth-source-search-collection
803 (aget alist "account")
806 (auth-source-search-collection
810 (aget alist "protocol")
813 (push (nreverse alist) result)
814 ;; to delete a line, we just comment it out
816 (goto-char (point-min))
825 (when auth-source-gpg-encrypt-to
826 ;; (see bug#7487) making `epa-file-encrypt-to' local to
827 ;; this buffer lets epa-file skip the key selection query
828 ;; (see the `local-variable-p' check in
829 ;; `epa-file-write-region').
830 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
831 (make-local-variable 'epa-file-encrypt-to))
832 (if (listp auth-source-gpg-encrypt-to)
833 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
835 ;; ask AFTER we've successfully opened the file
836 (when (y-or-n-p (format "Save file %s? (%d modifications)"
838 (write-region (point-min) (point-max) file nil 'silent)
839 (auth-source-do-debug
840 "auth-source-netrc-parse: modified %d lines in %s"
843 (nreverse result))))))
845 (defun auth-source-netrc-normalize (alist)
846 (mapcar (lambda (entry)
848 (while (setq item (pop entry))
853 (setq k (cond ((member k '("machine")) "host")
854 ((member k '("login" "account")) "user")
855 ((member k '("protocol")) "port")
856 ((member k '("password")) "secret")
859 ;; send back the secret in a function (lexical binding)
860 (when (equal k "secret")
861 (setq v (lexical-let ((v v))
864 (setq ret (plist-put ret
865 (intern (concat ":" k))
871 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
874 (defun* auth-source-netrc-search (&rest
876 &key backend create delete
877 type max host user port
879 "Given a property list SPEC, return search matches from the :backend.
880 See `auth-source-search' for details on SPEC."
881 ;; just in case, check that the type is correct (null or same as the backend)
882 (assert (or (null type) (eq type (oref backend type)))
883 t "Invalid netrc search: %s %s")
885 (let ((results (auth-source-netrc-normalize
886 (auth-source-netrc-parse
889 :file (oref backend source)
892 :port (or port t)))))
894 ;; if we need to create an entry AND none were found to match
898 ;; create based on the spec and record the value
900 ;; if the user did not want to create the entry
901 ;; in the file, it will be returned
902 (apply (slot-value backend 'create-function) spec)
903 ;; if not, we do the search again without :create
904 ;; to get the updated data.
906 ;; the result will be returned, even if the search fails
907 (apply 'auth-source-netrc-search
908 (plist-put spec :create nil)))))
911 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
912 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
914 (defun* auth-source-netrc-create (&rest spec
916 secret host user port create
918 (let* ((base-required '(host user port secret))
919 ;; we know (because of an assertion in auth-source-search) that the
920 ;; :create parameter is either t or a list (which includes nil)
921 (create-extra (if (eq t create) nil create))
922 (required (append base-required create-extra))
923 (file (oref backend source))
925 ;; `valist' is an alist
927 ;; `artificial' will be returned if no creation is needed
930 ;; only for base required elements (defined as function parameters):
931 ;; fill in the valist with whatever data we may have from the search
932 ;; we complete the first value if it's a list and use the value otherwise
933 (dolist (br base-required)
934 (when (symbol-value br)
935 (let ((br-choice (cond
936 ;; all-accepting choice (predicate is t)
937 ((eq t (symbol-value br)) nil)
938 ;; just the value otherwise
939 (t (symbol-value br)))))
941 (aput 'valist br br-choice)))))
943 ;; for extra required elements, see if the spec includes a value for them
944 (dolist (er create-extra)
945 (let ((name (concat ":" (symbol-name er)))
946 (keys (loop for i below (length spec) by 2
947 collect (nth i spec))))
949 (when (equal (symbol-name k) name)
950 (aput 'valist er (plist-get spec k))))))
952 ;; for each required element
954 (let* ((data (aget valist r))
955 ;; take the first element if the data is a list
956 (data (if (listp data)
959 ;; this is the default to be offered
960 (given-default (aget auth-source-creation-defaults r))
961 ;; the default supplementals are simple: for the user,
962 ;; try (user-login-name), otherwise take given-default
964 ((and (not given-default) (eq r 'user))
968 ;; store the data, prompting for the password if needed
971 ((and (null data) (eq r 'secret))
972 ;; special case prompt for passwords
973 (read-passwd (format "Password for %s@%s:%s: "
974 (or (aget valist 'user) "[any user]")
975 (or (aget valist 'host) "[any host]")
976 (or (aget valist 'port) "[any port]"))))
980 (setq artificial (plist-put artificial
981 (intern (concat ":" (symbol-name r)))
983 (lexical-let ((data data))
987 ;; when r is not an empty string...
988 (when (and (stringp data)
990 ;; this function is not strictly necessary but I think it
991 ;; makes the code clearer -tzz
992 (let ((printer (lambda ()
993 ;; append the key (the symbol name of r)
994 ;; and the value in r
997 (if (zerop (length add)) "" " ")
998 ;; remap auth-source tokens to netrc
1002 ('secret "password")
1003 ('port "port") ; redundant but clearer
1004 (t (symbol-name r)))
1005 ;; the value will be printed in %S format
1007 (setq add (concat add (funcall printer)))))))
1010 (when (file-exists-p file)
1011 (insert-file-contents file))
1012 (when auth-source-gpg-encrypt-to
1013 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1014 ;; this buffer lets epa-file skip the key selection query
1015 ;; (see the `local-variable-p' check in
1016 ;; `epa-file-write-region').
1017 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1018 (make-local-variable 'epa-file-encrypt-to))
1019 (if (listp auth-source-gpg-encrypt-to)
1020 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1021 (goto-char (point-max))
1023 ;; ask AFTER we've successfully opened the file
1026 (setq k (read-char-choice
1027 (format "Add to file %s? %s: "
1029 "(y)es/(n)o but use it/(e)dit line/(s)kip file")
1037 (?e (setq add (read-string "Line to add: " add)))
1040 (when (< 0 (length add))
1045 (write-region (point-min) (point-max) file nil 'silent)
1046 (auth-source-do-warn
1047 "auth-source-netrc-create: wrote 1 new line to %s"
1052 (list artificial))))))
1054 ;;; Backend specific parsing: Secrets API backend
1056 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1057 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1058 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1059 ;;; (let ((auth-sources '(default))) (auth-source-search))
1060 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1061 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1063 (defun* auth-source-secrets-search (&rest
1065 &key backend create delete label
1066 type max host user port
1068 "Search the Secrets API; spec is like `auth-source'.
1070 The :label key specifies the item's label. It is the only key
1071 that can specify a substring. Any :label value besides a string
1072 will allow any label.
1074 All other search keys must match exactly. If you need substring
1075 matching, do a wider search and narrow it down yourself.
1077 You'll get back all the properties of the token as a plist.
1079 Here's an example that looks for the first item in the 'Login'
1082 \(let ((auth-sources '(\"secrets:Login\")))
1083 (auth-source-search :max 1)
1085 Here's another that looks for the first item in the 'Login'
1086 Secrets collection whose label contains 'gnus':
1088 \(let ((auth-sources '(\"secrets:Login\")))
1089 (auth-source-search :max 1 :label \"gnus\")
1091 And this one looks for the first item in the 'Login' Secrets
1092 collection that's a Google Chrome entry for the git.gnus.org site
1093 authentication tokens:
1095 \(let ((auth-sources '(\"secrets:Login\")))
1096 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1100 (assert (not create) nil
1101 "The Secrets API auth-source backend doesn't support creation yet")
1103 ;; (secrets-delete-item coll elt)
1104 (assert (not delete) nil
1105 "The Secrets API auth-source backend doesn't support deletion yet")
1107 (let* ((coll (oref backend source))
1108 (max (or max 5000)) ; sanity check: default to stop at 5K
1109 (ignored-keys '(:create :delete :max :backend :label))
1110 (search-keys (loop for i below (length spec) by 2
1111 unless (memq (nth i spec) ignored-keys)
1112 collect (nth i spec)))
1113 ;; build a search spec without the ignored keys
1114 ;; if a search key is nil or t (match anything), we skip it
1115 (search-spec (apply 'append (mapcar
1117 (if (or (null (plist-get spec k))
1118 (eq t (plist-get spec k)))
1120 (list k (plist-get spec k))))
1122 ;; needed keys (always including host, login, port, and secret)
1123 (returned-keys (mm-delete-duplicates (append
1124 '(:host :login :port :secret)
1126 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1127 unless (and (stringp label)
1128 (not (string-match label item)))
1130 ;; TODO: respect max in `secrets-search-items', not after the fact
1131 (items (butlast items (- (length items) max)))
1132 ;; convert the item name to a full plist
1133 (items (mapcar (lambda (item)
1135 ;; make an entry for the secret (password) element
1138 (lexical-let ((v (secrets-get-secret coll item)))
1140 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1142 (mapcar (lambda (entry)
1143 (list (car entry) (cdr entry)))
1144 (secrets-get-attributes coll item)))))
1146 ;; ensure each item has each key in `returned-keys'
1147 (items (mapcar (lambda (plist)
1150 (mapcar (lambda (req)
1151 (if (plist-get plist req)
1159 (defun* auth-source-secrets-create (&rest
1161 &key backend type max host user port
1164 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1169 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1171 ;; deprecate the old interface
1172 (make-obsolete 'auth-source-user-or-password
1173 'auth-source-search "Emacs 24.1")
1174 (make-obsolete 'auth-source-forget-user-or-password
1175 'auth-source-forget "Emacs 24.1")
1177 (defun auth-source-user-or-password
1178 (mode host port &optional username create-missing delete-existing)
1179 "Find MODE (string or list of strings) matching HOST and PORT.
1181 DEPRECATED in favor of `auth-source-search'!
1183 USERNAME is optional and will be used as \"login\" in a search
1184 across the Secret Service API (see secrets.el) if the resulting
1185 items don't have a username. This means that if you search for
1186 username \"joe\" and it matches an item but the item doesn't have
1187 a :user attribute, the username \"joe\" will be returned.
1189 A non nil DELETE-EXISTING means deleting any matching password
1190 entry in the respective sources. This is useful only when
1191 CREATE-MISSING is non nil as well; the intended use case is to
1192 remove wrong password entries.
1194 If no matching entry is found, and CREATE-MISSING is non nil,
1195 the password will be retrieved interactively, and it will be
1196 stored in the password database which matches best (see
1199 MODE can be \"login\" or \"password\"."
1200 (auth-source-do-debug
1201 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1202 mode host port username)
1204 (let* ((listy (listp mode))
1205 (mode (if listy mode (list mode)))
1207 (format "%s %s:%s %s" mode host port username)
1208 (format "%s %s:%s" mode host port)))
1209 (search (list :host host :port port))
1210 (search (if username (append search (list :user username)) search))
1211 (search (if create-missing
1212 (append search (list :create t))
1214 (search (if delete-existing
1215 (append search (list :delete t))
1217 ;; (found (if (not delete-existing)
1218 ;; (gethash cname auth-source-cache)
1219 ;; (remhash cname auth-source-cache)
1224 (auth-source-do-debug
1225 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1227 ;; don't show the password
1228 (if (and (member "password" mode) t)
1232 found) ; return the found data
1233 ;; else, if not found, search with a max of 1
1234 (let ((choice (nth 0 (apply 'auth-source-search
1235 (append '(:max 1) search)))))
1239 ((equal "password" m)
1240 (push (if (plist-get choice :secret)
1241 (funcall (plist-get choice :secret))
1244 (push (plist-get choice :user) found)))))
1245 (setq found (nreverse found))
1246 (setq found (if listy found (car-safe found)))))
1250 (provide 'auth-source)
1252 ;;; auth-source.el ends here